2011-10-05 180 views
1

在C#中,如何從Excel文件的工作表中獲取列名?從Excel工作表中獲取列名

這裏是我到目前爲止的代碼:

ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", "@"C:\file.xlsx"); 

objConn.Open(); 
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM ["xlWorksheet"$]", objConn); 

OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(); 

objAdapter1.SelectCommand = objCmdSelect; 

DataSet objDataset1 = new DataSet(); 

objAdapter1.Fill(objDataset1); 

objConn.Close(); 
+0

[從c#中的excel文件中讀取列名稱]的可能的重複(http://stackoverflow.com/questions/3855101/read-column-names-from-excel-file-in-c) – codingbadger

回答

4

請問您連接字符串包含HDR = YES

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES"; 

一旦你填入你的數據表或數據集,你可以把平常方法:

dt.Columns[0].ColumnName 

或者:

// For each DataTable, print the ColumnName. 
foreach(DataTable table in dataSet.Tables) 
{ 
    foreach(DataColumn column in table.Columns) 
    { 
     Console.WriteLine(column.ColumnName); 
    } 
} 

而且這看起來不語法正確:

OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM ["xlWorksheet"$]", objConn); 

應該是這樣的:

OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + xlWorksheet + "$]", objConn); 

最後,如果您的時間 - 調查EPPlus(開放源代碼)進行讀/寫Excel - http://epplus.codeplex.com,因爲它可以在32位和64位環境中工作。

+0

這可行。謝謝! –