How to import all the Excel sheets to DataSet in C#

后端 未结 5 1965
终归单人心
终归单人心 2020-12-03 06:00

I\'ve searched internet for this and couldn\'t really find a question like it. Everyone was looking for a way to import an individual sheet in the excel file but what I want

5条回答
  •  悲哀的现实
    2020-12-03 06:28

    This is a code I came up with and it works perfect but I saw someone else already added an answer:

    static DataSet Parse(string fileName)
    {
        string connectionString = string.Format("provider=Microsoft.Jet.OLEDB.4.0; data source={0};Extended Properties=Excel 8.0;", fileName);
    
    
        DataSet data = new DataSet();
    
        foreach(var sheetName in GetExcelSheetNames(connectionString))
        {
            using (OleDbConnection con = new OleDbConnection(connectionString))
            {    
                var dataTable = new DataTable();
                string query = string.Format("SELECT * FROM [{0}]", sheetName);
                con.Open();
                OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
                adapter.Fill(dataTable);
                data.Tables.Add(dataTable);
            }
        }
    
        return data;
    }
    
    static string[] GetExcelSheetNames(string connectionString)
    {
            OleDbConnection con = null;
            DataTable dt = null;
            con= new OleDbConnection(connectionString);
            con.Open();
            dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    
            if (dt == null)
            {
                return null;
            }
    
            String[] excelSheetNames = new String[dt.Rows.Count];
            int i = 0;
    
            foreach (DataRow row in dt.Rows)
            {
                excelSheetNames[i] = row["TABLE_NAME"].ToString();
                i++;
            }
    
            return excelSheetNames;
    }
    

提交回复
热议问题