我有一个包含以下数据的csv文件:
FIBO.csv
41,3
36445122,EURUSD,4,0.01,1.05828,1,1.00881,10,66
36445121,EURUSD,4,0.01,1.05828,1,1.00881,10,66
36445120,EURUSD,4,0.01,1.05828,1,1.00881,10,66
当我使用OLEDB
提供程序读取此文件时,它会正确返回完美的数据表。
该代码在这里:
public DataTable CsvFileToDatatable(string path, bool IsFirstRowHeader)
{
string header = "No";
string sql = string.Empty;
DataTable dataTable = new DataTable();
string pathOnly = string.Empty;
string fileName = string.Empty;
try
{
pathOnly = System.IO.Path.GetDirectoryName(path);
fileName = System.IO.Path.GetFileName(path);
sql = @"SELECT * FROM [" + fileName + "]";
if (IsFirstRowHeader)
{
header = "Yes";
}
using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;IMEX = 1;HDR=" + header + "\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
}
}
}
}
catch
{
if (dataTable == null)
dataTable = new DataTable();
}
finally
{
}
return dataTable;
}
但是当csv文件具有如下值时:
41,3
36445122,EURUSD,4,0.01,1.05828,1,1.00881,10,66
然后返回的数据表缺少 EURUSD 。
如果我添加另一行,则所有数据都会完美返回。只有当我有两行时才会出现问题,就像上面那样。
我有几个像这样的文件,它们都有同样的问题。我不确定这有什么问题。
我已设置IMEX=1
,但无效。
答案 0 :(得分:0)
正如here所述,它似乎是来自JET.OLEDB.4的错误。
请检查此第三方库KBCsv,而不是使用OleDbConnection。我试过它如下,它起作用了:
FileStream stream = new FileStream(ope.FileName, FileMode.Open);
using (CsvReader reader = new CsvReader(stream))
{
while (reader.HasMoreRecords)
{
DataRecord record = reader.ReadDataRecord();
string row0 = record[0];
string row1 = record[1];
Console.WriteLine($"{row0}, {row1}");
}
}
以下是运行上面代码后的输出:
41,3
36445122,EURUSD