2011-12-08 21 views
2

我有一個Excel文件,列有名稱(數據源不受我控制..它是由客戶端給我的)。雖然列更改,但列標題不會更改。C#並從一個Excel文件中讀取值

在文件中,這就是所謂的「名」

如何訪問數據的每一個細胞都在同一列中?

+0

擡起頭:Excel列「頭」都沒有類似於數據庫列名 - 他們只是普通的細胞,「標題」在他們的文字。因此,您需要閱讀第一行單元格中的文本以獲取「標題」。循環遍歷第一行中的單元格,尋找具有所需標題文本的單元格。然後,一旦找到其text =列名稱的單元格,就知道它下面的列包含數據 – bernie2436

+0

Interop,OLE,other? –

回答

4

打開Excel文件作爲數據庫。然後,你就不必理會列的位置:

string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\MyExcelFile.xls;Extended Properties=\"Excel 8.0;HDR=YES\""; 
using (var conn = new System.Data.OleDb.OleDbConnection(connString)) { 
    conn.Open(); 
    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("Select * From [SheetName$]", conn); 
    OleDbDataReader reader = cmd.ExecuteReader(); 
    int firstNameOrdinal = reader.GetOrdinal("First Name"); 
    int lastNameOrdinal = reader.GetOrdinal("Last Name"); 
    while (reader.Read()) { 
     Console.WriteLine("First Name: {0}, Last Name: {1}", 
      reader.GetString(firstNameOrdinal), 
      reader.GetString(lastNameOrdinal)); 
    } 
} 
+0

這對我來說很合適,但我必須將構建配置從'AnyCPU'更改爲'x86'。顯然Microsoft.Jet.OLEDB.4.0在運行x64時不可用。 –

+0

是的,不幸的是,Jet沒有64位接口。 –

0

你可以做這樣的事情在您使用ODBC連接到該文件,並下載片的內容。

private bool DownloadExcelData(string fileName, ref DataTable informationDT) 
      { 
       // bool success 
       bool success = true; 

       // open the file via odbc 
       string connection = ConfigurationManager.ConnectionStrings["xls"].ConnectionString; 
       connection = String.Format(connection, FilePath + fileName); 
       OleDbConnection conn = new OleDbConnection(connection); 
       conn.Open(); 

       try 
       { 
        // retrieve the records from the first page 
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Information$]", conn); 
        OleDbDataAdapter adpt = new OleDbDataAdapter(cmd); 
        adpt.Fill(informationDT); 
       } 
       catch { success = false; } 

       // close the connection 
       conn.Close(); 
       return success; 
      } 

這裏是XLS和XLSX文件的一些示例ODBC連接:

<add name="xls" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;'" /> 
    <add name="xlsx" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0" />