我使用以下方法读取Csv文件内容:
/// <summary>
/// Reads data from a CSV file to a datatable
/// </summary>
/// <param name="filePath">Path to the CSV file</param>
/// <returns>Datatable filled with data read from the CSV file</returns>
public DataTable ReadCsv(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
log.Error("Invalid CSV file name.");
return null;
}
try
{
DataTable dt = new DataTable();
string folder = FileMngr.Instance.ExtractFileDir(filePath);
string fileName = FileMngr.Instance.ExtractFileName(filePath);
string connectionString =
string.Concat(@"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=",
folder, ";");
using (OdbcConnection conn =
new System.Data.Odbc.OdbcConnection(connectionString))
{
string selectCommand = string.Concat("select * from [", fileName, "]");
using (OdbcDataAdapter da = new OdbcDataAdapter(selectCommand, conn))
{
da.Fill(dt);
}
}
return dt;
}
catch (Exception ex)
{
log.Error("Error loading CSV content", ex);
return null;
}
}
如果我的 UTF-8 编码的Csv文件带有 schema.ini ,则此方法有效,如下所示:
[Example.csv]
Format=Delimited(,)
ColNameHeader=True
MaxScanRows=2
CharacterSet=ANSI
如果我在带有 Unicode 编码的Csv文件中有德语字符,则该方法无法正确读取数据。
我可以对上述读取 Unicode Csv文件的方法进行哪些修改?如果没有办法这样做,你能建议什么样的Csv阅读代码?
答案 0 :(得分:8)
尝试在schema.ini文件中使用CharacterSet=UNICODE
。虽然这不是documented on MSDN,但根据此thread on Microsoft Forums可行。
答案 1 :(得分:3)
嗯,一个非常好用且流量很好的流式CSV阅读器is on CodeProject;这是我尝试的第一件事......但听起来你的编码可能会被剔除,这可能不会让它变得简单......当然,它可能只是破坏了,在这种情况下上面可能会有效细
对于简单的CSV,您可以尝试自己解析它(string.Split
等),但是有足够的边缘情况可以使用预卷解析器。