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

我正在开发一个SharePoint工作流,第一步要求我打开一个Excel工作簿并阅读两件事:一系列类别(从名称范围,方便地,类别)和类别索引(在命名范围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();

不要过于严厉地判断代码本身;它经历了很多.无论如何,第一个命令永远不会正确执行.它没有抛出异常.它只返回一个空数据集. (HasRows为true,Read()返回false,但没有数据)第二个命令完美.这些都是命名范围.

然而,它们的填充方式不同.有一个Web服务调用填充类别.这些值显示在下拉框中.所选索引进入CategoryIndex.经过几个小时的敲击,我决定编写几行代码,以便下拉列表的值进入另一个单元格,然后我使用几行C#将值复制到CategoryIndex中,以便数据设置相同.结果证明这也是一条死胡同.

我错过了什么吗?为什么一个查询工作完美,另一个查询无法返回任何数据?

最佳答案 我发现了这个问题. Excel显然无法解析单元格中的值,因此它什么也没有返回.我要做的是将连接字符串调整为以下内容:

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

如果它会抛出一个异常或给出任何失败原因的指示,那将会有所帮助,但现在已经不合时宜了. IMEX = 1选项告诉Excel仅将所有值视为字符串.我很有能力解析我自己的整数,而不是Excel,所以我不需要它的帮助.

点赞