如何使用C#和OleDbConnection读取.xlsx和.xls文件?

时间:2017-05-02 00:07:16

标签: c# excel oledbconnection

以前我使用ExcelPackage从.xlsx文件中读取数据。这工作正常但后来我意识到ExcelPackage不能使用旧的.xls格式。所以我升级为使用OleDbConnection代替ExcelPackage,如下所示:

var file = HttpContext.Current.Request.Files[0];
DataTable sheetData = new DataTable();
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
    file.FileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"";

using (OleDbConnection conn = new OleDbConnection(connStr))
{
    conn.Open();
    DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    string sheetName = dtSchema.Rows[0].Field("TABLE_NAME");
    OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
    sheetAdapter.Fill(sheetData);
}

基本上只是尝试阅读那里的第一个电子表格。但是我在异常中得到了这个错误:

Cannot update. Database or object is read-only.

我做错了什么?那里隐藏着某种类型的更新操作吗?

3 个答案:

答案 0 :(得分:1)

试试这个:

OleDbConnection connection;
OleDbCommand command;
OleDbDataReader dr;

        string commandText = "SELECT * FROM [Sheet1$]";
        string oledbConnectString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
        @"Data Source=" + filename + ";" +
        "Extended Properties=\"Excel 12.0;HDR=YES\";";
        connection = new OleDbConnection(oledbConnectString);
        command = new OleDbCommand(commandText, connection);

        try
        {
            connection.Open();
            dr = command.ExecuteReader();

            while (dr.Read())
            {
                count++;

                for (int i = 1; i < dr.VisibleFieldCount; i++)
                {
                   Console.Writeln(""+dr[i].ToString());
                }
            }

            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("" + ex.Message);
            connection.Close();
        }

答案 1 :(得分:0)

以下是从给定的Excel文件路径返回DataSet的示例方法。返回的DataSet应将工作簿中的每个Excel工作表作为DataTable中的DataSet。这似乎工作正常,希望它可能有所帮助。

private DataSet GetExcelDataSet(string path) {
  string sheetName;
  string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path +
                        "; Jet OLEDB:Engine Type = 5; Extended Properties =\"Excel 8.0;\"";
  DataSet ds = new DataSet();
  using (OleDbConnection con = new OleDbConnection(ConnectionString)) {
    using (OleDbCommand cmd = new OleDbCommand()) {
      using (OleDbDataAdapter oda = new OleDbDataAdapter()) {
        cmd.Connection = con;
        con.Open();
        DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        for (int i = 0; i < dtExcelSchema.Rows.Count; i++) {
          sheetName = dtExcelSchema.Rows[i]["TABLE_NAME"].ToString();
          DataTable dt = new DataTable(sheetName);
          cmd.Connection = con;
          cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
          oda.SelectCommand = cmd;
          oda.Fill(dt);
          dt.TableName = sheetName;
          ds.Tables.Add(dt);
        }
      }
    }
  }
  return ds;
}

答案 2 :(得分:0)

个人而言,我发现很难使用带有OleDbConnections的Excel电子表格。

我想提供一个很好的开源免费ExcelMapper 替代方案。

与OLE查询相比,它提供了一种更加简洁(即可读)的读取Excel文件的方式。

1。给定一个Excel文件

enter image description here

2。创建一个Person C#对象:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

3。使用ExcelMapper进行阅读

  var fileName = @"C:\Temp\Names.xlsx"; // your excel file
  List<Person> people = new ExcelMapper(fileName).Fetch<Person>();

您还可以通过简单地传入一个额外的工作表参数来读取其他工作表:

  var fileName = @"C:\Temp\Names.xlsx"; // your excel file
  List<Person> people = new ExcelMapper(fileName).Fetch<Person>("Sheet2");

您可以使用NuGet进行安装

Install-Package ExcelMapper

免责声明:我没有与ExcelMapper关联,但是在尝试了各种不同的库之后,我发现该库最容易使用。