2011-07-22 52 views
2

我想用閱讀在C#中的Excel文件下面的代碼查詢Excel工作表在c#

string excelFileName = "Book2.xls"; 
string excelConnectString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Book2.xls;Extended Properties=""Excel 8.0;HDR=YES;"""; 
//string excelConnectString = @"Provider = Microsoft.Jet.OLEDB.4.0;Data Source = " + excelFileName + ";" + "Extended Properties = Excel 8.0; HDR=Yes;IMEX=1"; 

OleDbConnection objConn = new OleDbConnection(excelConnectString); 
OleDbCommand objCmd = new OleDbCommand("Select * From [Sheet1$]", objConn); 

OleDbDataAdapter objDatAdap = new OleDbDataAdapter(); 
objDatAdap.SelectCommand = objCmd; 
DataSet ds = new DataSet(); 
objDatAdap.Fill(ds); 

enter image description here

一切工作fine.Now我的要求是讀取Excel文件類似下面

SELECT A,B,D From [Sheet1]; 
+0

你想使用列名搜索? – Anuraj

+0

@Anuraj:沒有像'從表中選擇A,B,C'的單元格 –

+2

我認爲你不能這樣做......一個小的解決方法是使一個「Select *」填充數據集,並從數據集... – 2GDev

回答

5

的選擇,命令應該是這樣的,如果你想讀A1到D1:

SELECT * FROM [SHEETNAME_HERE$A1:D1] 

整個代碼:

   OleDbConnection con = new OleDbConnection(
        "provider=Microsoft.Jet.OLEDB.4.0;data source=" 
        + XLS_FILE_NAME_AND_PATH_HERE 
        + ";Extended Properties=Excel 8.0;"); 

       StringBuilder stbQuery = new StringBuilder(); 
       stbQuery.Append("SELECT * FROM [" + SHEETNAME_HERE + "$A1:D1]"); 
       OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con); 

       DataSet dsXLS = new DataSet(); 
       adp.Fill(dsXLS); 

       DataView dvEmp = new DataView(dsXLS.Tables[0]); 

       dataGridView1.DataSource = dvEmp; 
2

你可以constuct使用查詢這樣的:

SELECT FirstName, LastName, Mobile FROM [Sheet1$] 

即將第一行值用作列名稱。

+0

@彼得Abudlin:謝謝你的答案,我編輯了我的問題(圖片),我不想按列名讀取數據,購買我想通過單元格讀取它(A,B,C ..) –

3
DataTable Contents = new DataTable(); 
using (OleDbDataAdapter adapter = new OleDbDataAdapter("Select * From [Sheet1$]", objConn)) 
{ 
    adapter.Fill(Contents); 
} 
Console.WriteLine(Contents.Rows[0][0]); 

你可以通過選擇特定的細胞適當的指數。