2009-06-17 77 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,所以我不需要它的幫助。

相關問題