Reading an Excel File From C#

后端 未结 5 838
我寻月下人不归
我寻月下人不归 2020-12-09 23:38

I have a connection string to read an excel file from my C# project that looks like this..

String ConnectionString  = \"Provider=Microsoft.ACE.OLEDB.12.0;\"          


        
5条回答
  •  春和景丽
    2020-12-09 23:44

    I recently had to use this provider for an Azure Web Job where I needed to use an OLEDB Provider rather than the Excel.

    You can install the Microsoft.ACE.OLEDB.12.0 Provider using the following setup.

    Microsoft Access Database Engine 2010 Redistributable https://www.microsoft.com/en-us/download/details.aspx?id=13255

    Once installed, you can modify the connection string for .xls and .xlsx file extensions.

    For example, the following code will convert an Excel file to a DataSet with a DataTable for each Worksheet in the excel file.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Configuration;
    using System.Data;
    using System.Data.OleDb;
    using System.Linq;
    using System.Net;
    

    ...

    public DataSet ExcelToDataSet(string excelFilename)
    {
        var dataSet = new DataSet(excelFilename);
    
        // Setup Connection string based on which excel file format we are using
        var excelType = "Excel 8.0";
        if (excelFilename.Contains(".xlsx"))
        {
            excelType = "Excel 12.0 XML";
        }
    
        // 
        var connectionStringFormat = ConfigurationManager.AppSettings["Microsoft.ACE.OLEDB"].ToString();
        var excelNamePath = string.Format(@"{0}\{1}", Environment.CurrentDirectory, excelFilename);
        var connectionString = string.Format(connectionStringFormat, excelNamePath, excelType);
    
        // Create a connection to the excel file
        using (var oleDbConnection = new OleDbConnection(connectionString))
        {
            // Get the excel's sheet names
            oleDbConnection.Open();
            var schemaDataTable = (DataTable)oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            oleDbConnection.Close();
            var sheetsName = GetSheetsName(schemaDataTable);
    
            // For each sheet name 
            OleDbCommand selectCommand = null;
            for (var i = 0; i < sheetsName.Count; i++)
            {
                // Setup select command
                selectCommand = new OleDbCommand();
                selectCommand.CommandText = "SELECT * FROM [" + sheetsName[i] + "]";
                selectCommand.Connection = oleDbConnection;
    
                // Get the data from the sheet
                oleDbConnection.Open();
                using (var oleDbDataReader = selectCommand.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    // Convert data to DataTable
                    var dataTable = new DataTable(sheetsName[i].Replace("$", "").Replace("'", ""));
                    dataTable.Load(oleDbDataReader);
    
                    // Add to Dataset
                    dataSet.Tables.Add(dataTable);
                }
            }
    
            return dataSet;
        }
    }
    
    private List GetSheetsName(DataTable schemaDataTable)
    {
        var sheets = new List();
        foreach(var dataRow in schemaDataTable.AsEnumerable())
        {
            sheets.Add(dataRow.ItemArray[2].ToString());
        }
    
        return sheets;
    }
    

提交回复
热议问题