为什么一个ADO.NET Excel查询工作,而另一个不工作?

我正在开发一个SharePoint工作stream程,第一步要求我打开一个Excel工作簿并阅读两件事:一系列类别(来自范围足够方便的Categories )和一个类别索引(在命名范围CategoryIndex )。 Categories是大约100个单元格的列表,而CategoryIndex是单个单元格。

我正在使用ADO.NET来查询工作簿

 string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + temporaryFileName + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES\""; OleDbConnection connection = new OleDbConnection(connectionString); connection.Open(); OleDbCommand categoryIndexCommand = new OleDbCommand(); categoryIndexCommand.Connection = connection; categoryIndexCommand.CommandText = "Select * From CategoryIndex"; OleDbDataReader indexReader = categoryIndexCommand.ExecuteReader(); if (!indexReader.Read()) throw new Exception("No category selected."); object indexValue = indexReader[0]; int categoryIndex; if (!int.TryParse(indexValue.ToString(), out categoryIndex)) throw new Exception("Invalid category manager selected"); OleDbCommand selectCommand = new OleDbCommand(); selectCommand.Connection = connection; selectCommand.CommandText = "SELECT * FROM Categories"; OleDbDataReader reader = selectCommand.ExecuteReader(); if (!reader.HasRows || categoryIndex >= reader.RecordsAffected) throw new Exception("Invalid category/category manager selected."); connection.Close(); 

不要太苛刻地判断代码本身; 它经历了很多。 无论如何,第一个命令永远不会正确执行。 它不会抛出exception。 它只是返回一个空的数据集。 ( HasRowstrueRead()返回false ,但那里没有数据)第二个命令完美地工作。 这些都是命名的范围。

然而,他们的人口是不一样的。 有一个networking服务电话,填写Categories 。 这些值显示在下拉框中。 所选的索引进入CategoryIndex 。 几小时后,我决定编写几行代码,以便将下拉列表的值input到另一个单元格中,然后使用几行C#将该值复制到CategoryIndex ,以便数据的设置完全相同。 原来这也是一个盲目的胡同。

我错过了什么吗? 为什么一个查询能正常工作,另一个查询不能返回任何数据?

我发现了这个问题。 Excel显然无法parsing单元格中的值,所以它什么也没有返回。 我必须做的是调整连接string到以下内容:

 string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + temporaryFileName + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=NO;IMEX=1\""; 

如果它会抛出一个例外,或给出它为什么会失败的迹象,那将是有帮助的,但是现在这一点已经不合时宜了。 IMEX=1选项告诉Excel只将所有值视为string。 我很有能力parsing自己的整数,谢谢你,Excel,所以我不需要它的帮助。