简体   繁体   中英

Reading Excel file with C# - Choose sheet

I'm reading an excel file with C# and OleDB (12.0). 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());
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM