无法使用 oledb 从 csv 读取所有列

cannot read all the columns from csv using oledb

我有一个包含以下内容的 csv 文件 header: "Pickup Date","Pickup Time","Pickup Address","From Zone",等等.. 除了使用 oledb,我只能阅读前两列。我使用了一个 schema.ini 文件,其中指定了所有列名。请建议。

这是我的示例 csv。

"PickupDate","PickupTime","PickupAddress","FromZone"
"11/05/15","4:00:00 AM","9 Houston Rd, CityName, NC 28262,","262"

这是我的代码:

Schema.ini
-----------
[ReportResults.csv]
ColNameHeader = True
Format = CSVDelimited
col1=Pickup Date DateTime
col2=Pickup Time Text width 100
col3=Pickup Address Text width 500
col4=FromZone short

oledb code
-----------      

     public static DataTable SelectCSV(string path, string query)
     {
      // since the file contains addresses with , the delimiter ", is used. Each cell is written within "" in  the file.
                  var strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path +
                                "; Extended Properties='text;HDR=Yes;FMT=Delimited(\",)'";

                  OleDbConnection selectConnection = (OleDbConnection)null;
                  OleDbDataAdapter oleDbDataAdapter = (OleDbDataAdapter)null;


                      selectConnection = new OleDbConnection(strConn);
                      selectConnection.Open();
                      using(OleDbCommand cmd=new OleDbCommand(query,selectConnection))
                      using (oleDbDataAdapter = new OleDbDataAdapter(cmd))
                      {
                          DataTable dt = new DataTable();
                          dt.Locale=CultureInfo.CurrentCulture;
                          oleDbDataAdapter.Fill(dt);
                          return dt;
                      }
    }

每列都包含在双引号中,因此双引号内的每个逗号都不会被视为分隔符。

所以您可以导入您的文件:

  • 不使用 schema.ini
  • 在连接字符串中指定 EXTENDED PROPERTIES='text;HDR=Yes;FMT=Delimited'

如果您需要使用模式来解决其他问题,请注意您的 schema.ini 形式上不正确;使用这样的东西:

[ReportResults.csv]
ColNameHeader = True
Format = CSVDelimited
col1=PickupDate DateTime
col2=PickupTime Text width 100
col3=PickupAddress Text width 500
col4=FromZone short

如果您在提取 DateTime 列时遇到问题,请指定 DateTimeFormat 选项;即,如果您的取件日期类似于 2015 年 11 月 13 日,请指定 DateTimeFormat=yyyy/MM/dd=yyyy/MM/dd.

如果您在提取 Short 列时遇到问题,请确认 FromZone 是一个介于 -32768 和 32767 之间的整数;如果不是,请使用不同的类型。如果小数点分隔符有问题,您也可以设置 DecimalSymbol 选项。

您可以在 MSDN 上找到更多信息。