簡體   English   中英

從C#讀取Excel文件

[英]Reading an Excel File From C#

我有一個連接字符串,可以從我的C#項目中讀取一個如下所示的Excel文件。

String ConnectionString  = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                                      "Data Source=" + VariableFile + ";" +
                                      "Extended Properties=Excel 8.0;";

我也有objConn.Open(); 打開文件..

問題是,如果我手動打開Excel文件並運行程序,則程序只有一次會打開文件。 任何人都可以幫助我從C#代碼中打開文件,而不必先手動打開它。 我收到錯誤消息:當我嘗試運行而不首先打開Excel文件的ISAM時,找不到可安裝的ISAM。

謝謝

我認為您的連接字符串格式錯誤,通常顯示“找不到可安裝的ISAM”。

試試看,這是從我擁有的一段操作代碼中得出的:

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);

最近,我不得不將此提供程序用於Azure Web作業,而我需要使用OLEDB提供程序而不是Excel。

您可以使用以下設置安裝Microsoft.ACE.OLEDB.12.0提供程序。

Microsoft Access數據庫引擎2010可再發行的https://www.microsoft.com/zh-cn/download/details.aspx?id=13255

安裝后,您可以修改.xls和.xlsx文件擴展名的連接字符串。

例如,下面的代碼將Excel文件中的每個工作表的Excel文件轉換為帶有DataTable的DataSet。

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;
}

以下代碼將讀取Excel文件並使用其數據填充DataTable

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);
            }

另一種選擇是使用專門的庫而不是創建連接。 看看EPPlus,它是一個開放源代碼庫,可以在C#中使用excel文件。 它對我來說非常有效。

http://epplus.codeplex.com/

在此鏈接中,您可以看到有關使用EPPlus讀取excel文件的示例:

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

有用於連接到Excel的不同提供程序。 也許您應該嘗試使用另一種。 在這里看看例子:

http://www.connectionstrings.com/excel

Excel的提供程序»Microsoft Jet OLE DB 4.0»ACE OLEDB 12.0»OLE DB的.NET Framework數據提供程序(OleDbConnection)»Microsoft Excel ODBC驅動程序»ODBC的.NET Framework數據提供程序(OdbcConnection)»Microsoft Excel的.NET xlReader(ExcelConnection) )

在您的情況下,您應該具有以下內容:Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\\ myFolder \\ myOldExcelFile.xls;擴展屬性=“ Excel 12.0; HDR = YES”;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM