2009-06-17 76 views
4

我正在开发一个SharePoint工作流程,第一步需要我打开一个Excel工作簿并阅读两件事:一系列类别(来自范围名为Categories的范围)和一个类别索引范围CategoryIndex)。 Categories是大约100个单元的列表,并且CategoryIndex是单个单元。为什么一个ADO.NET Excel查询工作而另一个不工作?

我使用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中,以便数据设置完全相同。结果这也是一个盲目的胡同。

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

回答

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

相关问题