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

时间:2009-06-17 13:46:29

标签: excel ado.net ado

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

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

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

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

1 个答案:

答案 0 :(得分:2)

我找到了这个问题。 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,所以我不需要它的帮助。

相关问题