Reading multiple excel sheets with different worksheet names

后端 未结 1 1854
無奈伤痛
無奈伤痛 2020-12-19 23:43

I would like to know how I can read multiple excel worksheet with different worksheet name in c# and with the used of oledb.

I have this existing way to read multipl

相关标签:
1条回答
  • 2020-12-20 00:03

    This is from VB.net but not sure how well it translates, returns a list of strings containing all sheet names:

    OleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
    

    MSDN Link

    Once you have a list of sheet names you can do a simple For Each loop to iterate.

    Edit:

    This should work in C#

    Add function

    static DataTable GetSchemaTable(string connectionString)
    {
        using (OleDbConnection connection = new 
                   OleDbConnection(connectionString))
        {
            connection.Open();
            DataTable schemaTable = connection.GetOleDbSchemaTable(
                OleDbSchemaGuid.Tables,
                new object[] { null, null, null, "TABLE" });
            return schemaTable;
        }
    }
    

    Your code would change to:

    DataSet ds = new DataSet();
    var excelConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0", path); 
    OleDbConnection connection = new OleDbConnection();
    connection.ConnectionString = excelConnectionString;
    
    DataTable sheets = GetSchemaTable(excelConnectionString);
    
    foreach (dataRow r in sheets.rows)
    {
        string query = "SELECT * FROM [" + r.Item(0).ToString + "]";
        ds.Clear();
        OleDbDataAdapter data = new OleDbDataAdapter(query, connection);
        data.Fill(ds);
    
    }
    

    Just be sure to do something with ds after each iteration.

    0 讨论(0)
提交回复
热议问题