2011-05-04 50 views
15

我新的C#和想讀在C#中使用下面的代碼的XLSX文件:讀取數據從XLSX在C#

string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=c:\\Temp\\source.xlsx;Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";"; 

//code to read the content of format file 
OleDbConnection con = new OleDbConnection(Connection); 
OleDbCommand command = new OleDbCommand(); 

DataTable dt = new DataTable(); 
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Tabelle1$]", con); 

myCommand.Fill(dt); 
Console.Write(dt.Rows.Count); 

我獲得TA校正從輸出計數,但我有2個問題:

1.如何做select select語句(如何訪問行)?

select * from [Tabelle1$] where A = '123' (A being an existing Excel row) 

將拋出一個錯誤提錯參數...

2.可有人爲我提供的教程鏈接或簡短的樣本如何訪問數據?

+0

請務必閱讀由尤金聯很好的教程。你會意識到爲什麼A ='123'不起作用(但是轉動HDR =否,並寫入WHERE F1 ='123'將) – nantito 2011-05-04 16:24:01

+0

我得到它與F1的工作,但不明白爲什麼A不工作,以及如何訪問默認表名... – 2011-05-05 07:45:50

+0

如果有HeaDer行,HDR表示。如果設置爲「是」,則表示不是設置自動「F1,F2 ...」,而是將第一行的單元格作爲列名稱的指示符。 – nantito 2011-05-05 15:05:23

回答

19

請參考下面的示例代碼:

private DataTable LoadXLS(string strFile, String sheetName, String column, String value) 
{ 
    DataTable dtXLS = new DataTable(sheetName); 

    try 
    { 
     string strConnectionString = ""; 

     if(strFile.Trim().EndsWith(".xlsx")) { 

      strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile); 

     } else if(strFile.Trim().EndsWith(".xls")) { 

      strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile); 

     } 

     OleDbConnection SQLConn = new OleDbConnection(strConnectionString); 

     SQLConn.Open(); 

     OleDbDataAdapter SQLAdapter = new OleDbDataAdapter(); 

     string sql = "SELECT * FROM [" + sheetName + "$] WHERE " + column + " = " + value; 

     OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn); 

     SQLAdapter.SelectCommand = selectCMD; 

     SQLAdapter.Fill(dtXLS); 

     SQLConn.Close(); 
    } 

    catch (Exception e) 
    { 
     Console.WriteLine(e.ToString()); 
    } 

    return dtXLS; 

} 
+0

爲您工作? – 2012-06-13 06:26:51

+0

我可以在哪裏下載oledb提供商? – 2012-10-12 09:26:37

+3

從http://www.microsoft.com/zh-CN/download/details.aspx?id=13255下載。 32位或64位取決於操作系統。 – 2012-10-12 12:05:59