从excel工作表中获取列名称

时间:2011-10-05 14:25:42

标签: c# excel oledb

在C#中,如何从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();

1 个答案:

答案 0 :(得分:4)

您的连接字符串是否包含 HDR = YES ?:

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

填充DataTable或DataSet后,您可以按常规方式处理:

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位环境。