从 C# 读取 Excel 文件

发布于 2024-12-02 04:03:50 字数 463 浏览 1 评论 0原文

我有一个连接字符串来从我的 C# 项目中读取一个 excel 文件,如下所示..

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

并且我还有 objConn.Open();打开文件..

问题是我的程序打开该文件的唯一时间是我手动打开 Excel 文件并运行我的程序。任何人都可以帮助我从 C# 代码打开该文件,而不必先手动打开它。当我尝试在不先打开 Excel 文件的情况下运行它时,收到错误消息:无法找到可安装的 ISAM。

谢谢

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;" +
                                      "Data Source=" + VariableFile + ";" +
                                      "Extended Properties=Excel 8.0;";

and I also have objConn.Open(); to open the file..

The problem is the only time my program will open the file is if I open the Excel file manually and run my program. Can anyone help me to open the file from my C# code instead of having to open it first manually. I get the error message: Could not find installable ISAM when I try to run it without opening the Excel file first.

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

骄傲 2024-12-09 04:03:50

我认为您的连接字符串格式错误,“无法找到可安装的 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);

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);
书间行客 2024-12-09 04:03:50

我最近不得不使用此提供程序来执行 Azure Web 作业,其中我需要使用 OLEDB 提供程序而不是 Excel。

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

Microsoft Access 数据库引擎 2010 可再发行组件
https://www.microsoft.com/en-us/download /details.aspx?id=13255

安装后,您可以修改 .xls 和 .xlsx 文件扩展名的连接字符串。

例如,以下代码将 Excel 文件转换为 DataSet,其中 Excel 文件中的每个工作表都有一个 DataTable。

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

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;
}
酒绊 2024-12-09 04:03:50

有不同的提供程序可用于连接到 Excel。也许您应该尝试使用不同的。
查看此处的示例:

http://www.connectionstrings.com/excel

Excel 提供程序
» 微软 Jet OLE DB 4.0
» ACE OLEDB 12.0
» 用于 OLE DB 的 .NET Framework 数据提供程序 (OleDbConnection)
» Microsoft Excel ODBC 驱动程序
» 用于 ODBC 的 .NET Framework 数据提供程序 (OdbcConnection)
» .NET xlReader for Microsoft Excel (ExcelConnection)

在您的情况下,您应该有这样的东西:
提供程序=Microsoft.ACE.OLEDB.12.0;数据源=c:\myFolder\myOldExcelFile.xls;扩展属性=“Excel 12.0;HDR=YES”;

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

辞慾 2024-12-09 04:03:50

以下代码将读取 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);
            }

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);
            }
£噩梦荏苒 2024-12-09 04:03:50

其他选择是使用专门的库而不是创建连接。看一下 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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文