【问题标题】:Why does one ADO.NET Excel query work and another does not?为什么一个 ADO.NET Excel 查询有效而另一个无效?
【发布时间】:2009-06-17 13:46:28
【问题描述】:

我正在处理 SharePoint 工作流,第一步需要我打开一个 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();

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

但是,它们的填充方式不同。有一个网络服务调用填满了Categories。这些值显示在下拉框中。所选索引进入CategoryIndex。经过几个小时的努力,我决定编写几行代码,以便下拉列表的值进入不同的单元格,然后我使用几行 C# 将值复制到CategoryIndex,这样数据就是设置相同。原来那也是一条死胡同。

我错过了什么吗?为什么一个查询可以完美运行,而另一个却无法返回任何数据?

【问题讨论】:

    标签: excel ado.net ado


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 2023-03-21
      • 1970-01-01
      • 2023-03-17
      • 2011-02-11
      相关资源
      最近更新 更多