3

我有一个 CSV 文件,其中有一列包含看起来像整数的字符串。也就是说,它们应该作为字符串处理,但由于它们是数字,它们似乎是作为整数导入的(去掉前导零)。

示例数据:

  • 0000000000079
  • 0000999000012
  • 0001002000005
  • 0004100000007

我看到的问题是最后一个示例数据点以 DBNull.Value 的形式出现。我假设这是因为 OleDB 将该列视为整数(数据点也没有前导零)并且 0004100000007 大于最大整数值。

有没有办法说“列 [0] 是一个字符串,不要把它读成整数”?读取数据时?

我目前使用的代码是:

OleDbConnection dbConn = new OleDbConnection(SourceConnectionString);
OleDbCommand dbCommand = new OleDbCommand("SELECT * FROM test.csv", dbConn);
dbConn.Open();
OleDbDataReader dbReader = dbCommand.ExecuteReader();

while (dbReader.Read())
{
    if (dbReader[0] != DBNull.Value)
    {
         // do some work
    }
}
4

5 回答 5

3

当您需要将列读取为字符串时,请尝试在阅读器中使用 GetString() 方法:

string myStringValue = reader.GetString(0);
于 2008-10-26T10:18:05.477 回答
1

Do you have control of the export process? If so can data be exported to CSV with quotes around the string items?

If this is a one of job then just import the file into a predfined SQL table using Integration Services, but I suspect this will be a recurring task.

于 2008-11-05T11:02:23.647 回答
1

有一个 Schema.ini 文件需要用于指定有关文件的信息。它包括字段类型和长度,是否有列标题以及字段分隔符是什么。

这是关于它的 MSDN 信息。
http://msdn.microsoft.com/en-us/library/ms709353.aspx

于 2009-02-23T12:56:19.823 回答
0

您是否尝试过使用此CSV 阅读器?它通常是非常受尊重的。也许试一试...

于 2008-10-26T09:10:02.617 回答
0

I'm no expert but do you cope with fixed file format ? http://csharptutorial.com/blog/exclusive-how-to-export-a-datatable-to-a-fixed-file-format-the-easy-way-using-odbc-or-jet-engine/

于 2011-04-17T17:43:51.753 回答