Reading an Excel File From C#

后端 未结 5 834
我寻月下人不归
我寻月下人不归 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:43

    Following Code will Read the Excel file & Fill DataTable with its data

    try
                {
                    string connectionString = string.Empty;
    
                    if (Path.GetExtension(ExcelFileName) == ".xlsx")
                    {
                        connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFileName +
                            ";Extended Properties=Excel 12.0;";
                    }
                    else
                    {
                        connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFileName + ";Extended Properties=Excel 8.0;";
                    }
    
                    OleDbCommand selectCommand = new OleDbCommand();
                    OleDbConnection connection = new OleDbConnection();
                    OleDbDataAdapter adapter = new OleDbDataAdapter();
                    connection.ConnectionString = connectionString;
    
                    if (connection.State != ConnectionState.Open)
                        connection.Open();
    
                    DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    
                    List<string> SheetsName = GetSheetsName(dtSchema);
                    for (int i = 0; i < SheetsName.Count; i++)
                    {
                        selectCommand.CommandText = "SELECT * FROM [" + SheetsName[i] + "]";
                        selectCommand.Connection = connection;
                        adapter.SelectCommand = selectCommand;
                        DataTable Sheet = new DataTable();
                        Sheet.TableName = SheetsName[i].Replace("$", "").Replace("'", "");
                        adapter.Fill(Sheet);
    
                        if (Sheet.Rows.Count > 0)
                        {
                            Records.Tables.Add(Sheet);                        
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteLog(ex);
                }
    
    0 讨论(0)
  • 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";
        }
    
        // <add key="Microsoft.ACE.OLEDB" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='{1};HDR=YES;READONLY=TRUE'"/>
        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<string> GetSheetsName(DataTable schemaDataTable)
    {
        var sheets = new List<string>();
        foreach(var dataRow in schemaDataTable.AsEnumerable())
        {
            sheets.Add(dataRow.ItemArray[2].ToString());
        }
    
        return sheets;
    }
    
    0 讨论(0)
  • 2020-12-09 23:56

    I think your connection string is formatted wrong and the "Could not find installable ISAM" is usually an indication of this.

    Try this, it's from a piece of operational code I have:

    Excel 2007

    string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=No;IMEX=1\";", fullPath);
    

    Excel 2003

    string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\";", fullPath);
    
    0 讨论(0)
  • 2020-12-10 00:01

    Other option would be to use a specialized library instead of creating a connection. Take a look on EPPlus, its an open source library to work with excel files in C#. It has worked very good to me.

    http://epplus.codeplex.com/

    And in this link you can see examples on reading excel files with EPPlus:

    http://blog.fryhard.com/archive/2010/10/28/reading-xlsx-files-using-c-and-epplus.aspx

    0 讨论(0)
  • 2020-12-10 00:08

    There are different providers for connecting to Excel. Maybe you should try using a different one. Have a look at the examples here:

    http://www.connectionstrings.com/excel

    Providers for Excel » Microsoft Jet OLE DB 4.0 » ACE OLEDB 12.0 » .NET Framework Data Provider for OLE DB (OleDbConnection) » Microsoft Excel ODBC Driver » .NET Framework Data Provider for ODBC (OdbcConnection) » .NET xlReader for Microsoft Excel (ExcelConnection)

    In your case you should have something like this: Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myOldExcelFile.xls;Extended Properties="Excel 12.0;HDR=YES";

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