Microsoft Jet数据库引擎无法找到对象' Sheet1 $ _'

时间:2015-11-17 13:13:46

标签: c# sql excel oledb

我正在从Excel文件中读取数据。当我读取普通的Excel文件时,它运行正常但是当我读取一个excel文件时,它有如下所示的列,它找不到工作表并给出异常 -

  

Microsoft Jet数据库引擎无法找到对象' Sheet1 $ _'。确保对象存在,并且您正确拼写其名称和路径名称。   enter image description here

阅读excel的我的代码是 -

  private static DataTable getExcelData(string ExcelPath)
    {
        OleDbConnection con;
        string connectionString;
        string[] pathArray = ExcelPath.Split('.');
        var Extention = pathArray[pathArray.Length - 1];
        if (Extention == "xlsx")
            //read a 2007 file
            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                ExcelPath + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
        else
            //read a 97-2003 file
            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                ExcelPath + ";Extended Properties=Excel 8.0;";

        con = new OleDbConnection(connectionString);

        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        DataTable dbSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null);
        var firstSheetName = dbSchema.Rows[0]["TABLE_NAME"];
        OleDbDataAdapter cmd = new OleDbDataAdapter("select * from [" + firstSheetName + "] Where NOT [Event Code]=''", con);
        DataSet ds = new DataSet();
        cmd.Fill(ds);
        con.Close();
        return ds.Tables[0];
    }

}

我必须得到Mon,Tues等内的所有专栏。

1 个答案:

答案 0 :(得分:3)

GetOleDbSchemaTable还会在Excel文件中返回隐藏的表格:通常,Sheet1$_这样的名称表示在Sheet1$上应用过滤器时创建的隐藏表格。

您需要更改代码:搜索以$结尾的表格以设置firstSheetName

请注意OLEDB does not preserve the sheet order as they were in Excel

另请注意,您需要执行此操作以读取包含多行标题的Excel文件:

  • 在您的连接字符串的HDR=No中设置EXTENDED PROPERTIES
  • 指定列名并在OleDbCommand中选择范围以跳过前两行

例如:

SELECT [F1] AS Location,
    [F2] AS EmpId,
    [F3] AS EmpName,
    [F4] AS MondayShift,
    [F5] AS Monday15Min,
    [F6] AS Monday30Min,
    [F7] AS Monday15Min2
FROM [Sheet1$A3:G]