问题
So far I have managed to get the column names of the whole excel file, but what I would like to do is to get the column names of the excel file of a given table (sheet). How could I modify the code to achieve this. I have been trying for a while now with no positive results, any help much appreciated.
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;
}
回答1:
You did not include sheet name in your code.
You can try below code:
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){
...
}
回答2:
You can do something like this:
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
}
}
}
来源:https://stackoverflow.com/questions/26295737/get-column-names-from-excel-file-of-a-specific-sheet-using-c-sharp-with-oledbcon