从C#读取Excel文件

时间:2011-08-30 16:19:41

标签: c# excel xlsx

我有一个连接字符串来读取我的C#项目中的excel文件,看起来像这样..

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

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

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

谢谢

5 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:2)

我最近不得不将此提供程序用于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文件转换为带有DataTable的DataSet,用于excel文件中的每个Worksheet。

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

答案 2 :(得分:1)

以下代码将阅读Excel文件&amp;用其数据填充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);
            }

答案 3 :(得分:1)

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

答案 4 :(得分:0)

连接到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) ».NET xlReader for Microsoft Excel(ExcelConnection)

在你的情况下你应该有这样的东西: Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\ myFolder \ myOldExcelFile.xls; Extended Properties =“Excel 12.0; HDR = YES”;

相关问题