CSV实际上是....分号分隔值...(在AZERTY上Excel导出)

Run*_*CMD 3 .net c# csv excel

我在这里有点困惑.

当我使用Excel 2003将工作表导出为CSV时,它实际上使用分号...

Col1;Col2;Col3
shfdh;dfhdsfhd;fdhsdfh
dgsgsd;hdfhd;hdsfhdfsh
Run Code Online (Sandbox Code Playgroud)

现在,当我使用Microsoft驱动程序读取csv时,它会使用逗号并将列表视为一个大列???

我怀疑Excel是用分号导出的,因为我有一个AZERTY键盘.但是,CSV读取器是否还必须考虑不同的分隔符?

我怎样才能知道合适的分隔符,和/或正确读取csv?

    public static DataSet ReadCsv(string fileName)
    {
        DataSet ds = new DataSet();
        string pathName = System.IO.Path.GetDirectoryName(fileName);
        string file = System.IO.Path.GetFileName(fileName);
        OleDbConnection excelConnection = new OleDbConnection
        (@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties=Text;");
        try
        {
            OleDbCommand excelCommand = new OleDbCommand(@"SELECT * FROM " + file, excelConnection);
            OleDbDataAdapter excelAdapter = new OleDbDataAdapter(excelCommand);
            excelConnection.Open();
            excelAdapter.Fill(ds);
        }
        catch (Exception exc)
        {
            throw exc;
        }
        finally 
        {
            if(excelConnection.State != ConnectionState.Closed )
                excelConnection.Close();
        }
        return ds;
    } 
Run Code Online (Sandbox Code Playgroud)

Ken*_*art 9

一种方法是使用一个像样的CSV库 ; 允许您指定分隔符的一个:

using (var csvReader = new CsvReader("yourinputfile.csv"))
{
    csvReader.ValueSeparator = ';';
    csvReader.ReadHeaderRecord();

    while (csvReader.HasMoreRecords)
    {
        var record = csvReader.ReadDataRecord():
        var col1 = record["Col1"];
        var col2 = record["Col2"];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我删除了官方的.NET 2.0支持,因为我想减少我的时间承诺.但是既然你想要它,我已经为你添加了2.0版本的最新版本.见http://kbcsv.codeplex.com/releases/view/36254 (3认同)