6

First, I want to say that I'm out on deep water here, since I'm just doing some changes to code that is written by someone else in the company, using OleDbDataAdapter to "talk" to Excel and I'm not familiar with that. There is one bug there I just can't follow.

I'm trying to use a OleDbDataAdapter to read in a excel file with around 450 lines.

In the code it's done like this:

connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source='" + path + "';" + "Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1;\"");
connection.Open();
OleDbDataAdapter objAdapter = new OleDbDataAdapter(objCommand.CommandText, connection);
objAdapter.Fill(objDataSet, "Excel");

foreach (DataColumn dataColumn in objTable.Columns) {
  if (dataColumn.Ordinal > objDataSet.Tables[0].Columns.Count - 1) {
    objDataSet.Tables[0].Columns.Add();
  }
  objDataSet.Tables[0].Columns[dataColumn.Ordinal].ColumnName = dataColumn.ColumnName;
  objImport.Columns.Add(dataColumn.ColumnName);
}

foreach (DataRow dataRow in objDataSet.Tables[0].Rows) {
   ...
}

Everything seems to be working fine except for one thing. The second column is filled with mostly four digit numbers like 6739, 3920 and so one, but fice rows have alphanumeric values like 8201NO and 8205NO. Those five cells are reported as having blank contents instead of their alphanumeric content. I have checked in excel, and all the cells in this columns are marked as Text.

This is an xls file by the way, and not xlsx.

Do anyone have any clue as why these cells are shown as blank in the DataRow, but the numeric ones are shown fine? There are other columns with alphanumeric content that are shown just fine.

4

3 回答 3

8

发生的事情是,excel 正在尝试根据该列中的前几个值将数据类型分配给电子表格列。我怀疑如果您查看该列中的属性,它会说它是一个数字列。

当您开始尝试使用 jet 查询该电子表格时,问题就出现了。当它认为它正在处理一个数字列并找到一个 varchar 值时,它会悄悄地什么也不返回。甚至没有一个神秘的错误消息可以关闭。

作为一种可能的解决方法,您可以将一个字母数值移动到第一行数据,然后尝试解析。我怀疑你会开始获取字母数字行的值然后......

看看这篇文章。它更详细地讨论了这个问题。它还谈到了一种可能的解决方法:

但是,根据 JET 文档,我们可以通过连接字符串覆盖注册表设置,如果我们设置 IMEX=1(作为扩展属性的一部分),则 JET 会将所有列类型设置为 UNICODE VARCHAR 或 ADVARWCHAR,而与“ImportMixedTypes”无关关键值。嘿嘿

于 2010-09-28T22:15:32.183 回答
1

IMEX=1意思是“将混合数据作为文本读取”。

然而,有一些陷阱。Jet 将仅使用几行来确定数据是否混合,如果发生这种情况,这些行都是数字,您将得到这种行为。

有关详细信息,请参阅connectionstrings.com

查看找到的[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel]注册表REG_DWORD“TypeGuessRows”。这是不让 Excel 仅使用前 8 行来猜测列数据类型的关键。将此值设置为 0 以扫描所有行。这可能会损害性能。另请注意,添加 IMEX=1 选项可能会导致 IMEX 功能仅在 8 行后设置。改用 IMEX=0 以确保强制注册表 TypeGuessRows=0(扫描所有行)工作。

于 2010-09-28T22:21:03.450 回答
1

如果可以的话,我建议不要使用 OleDb 数据提供程序来访问 Excel。由于其他人指出的原因,我除了问题之外什么都没有。当您处理大型电子表格时,性能也往往很糟糕。

你可以试试这个开源解决方案: http ://exceldatareader.codeplex.com/

于 2010-09-28T23:24:26.097 回答