到目前为止,我已经设法获得了整个excel文件的列名,但我想做的是获得给定表(表)的excel文件的列名称。我该如何修改代码来实现这一点。我已经尝试了一段时间,但没有任何积极的结果,非常感谢任何帮助。
public static List<String> ReadSpecificTableColumns(string filePath, string sheetName)
{
var columnList = new List<string>();
try
{
var excelConnection = new OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + filePath + "';Extended Properties='Excel 12.0;IMEX=1'");
excelConnection.Open();
var columns = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null);
excelConnection.Close();
if (columns != null)
{
columnList.AddRange(from DataRow column in columns.Rows select column["Column_name"].ToString());
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
return columnList;
}
您的代码中没有包含工作表名称
您可以尝试以下代码:
var adapter = new OleDbDataAdapter("SELECT * FROM [" +sheetName + "$]", excelConnection);
var ds = new DataSet();
adapter.Fill(ds, "myTable");
DataTable data = ds.Tables["myTable"];
foreach(DataColumn dc in data.Columns){
...
}
使用这样的代码段:怎么样
var adapter = new OleDbDataAdapter("SELECT * FROM [" +sheetName + "$A1:Z1]", excelConnection);
var table = new DataTable();
adapter.Fill(table);
对于具有"0"的连接字符串;HDR=是";它将读取第一行,目标表将包含所有列,但没有数据。
您可以这样做:
private void ValidateExcelColumns(string filePath)
{
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties="Excel 12.0;IMEX=1;HDR=Yes;TypeGuessRows=0;ImportMixedTypes=Text""; ;
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
DataTable dt = new DataTable();
var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT TOP 1 * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
var adapter = new OleDbDataAdapter(cmd);
adapter.Fill(dt);
}
foreach(DataColumn column in dt.Columns)
{
//Do something with your columns
}
}
}