c# – 无法使用oledb读取csv中的所有列

我有一个带有以下标题的csv文件:

    “取件日期”,“取件时间”,“取件地址”,“从区域”等等.

    我只能阅读前2列,除了使用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.

如果您在提取短列时遇到问题,请确认FromZone是介于-32768和32767之间的整数;如果没有,请使用其他类型.如果小数分隔符有问题,也可以设置DecimalSymbol选项.

您可以在MSDN找到更多信息.

点赞