Reading Excel file with C# - Choose sheet
I'm reading an excel file with C# and OleDB (12.0).开发者_如何学JAVA There I have to specify the select statement with the name of the sheet I wish to read ([Sheet1$]
).
this.dataAdapter =
new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
Is it possible to select the first sheet, no matter what name?
Thank you.
See this answer on how to get the list of sheet names in order: Using Excel OleDb to get sheet names IN SHEET ORDER
And here's my version which is a little shorter:
public static IEnumerable<string> GetExcelSheetNames(string excelFile)
{
var connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
using (var connection = new OleDbConnection(connectionString))
{
connection.Open();
using (var dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))
{
return (dt ?? new DataTable())
.Rows
.Cast<DataRow>()
.Select(row => row["TABLE_NAME"].ToString());
}
}
}
精彩评论