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

The Microsoft Jet database engine could not find the object 'Sheet1$_'

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

The Microsoft Jet database engine could not find the object 'Sheet1$_'. Make sure the object exists and that you spell its name and the path name correctly.

我阅读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];
    }

}

我必须获取周一、周二等的所有列

GetOleDbSchemaTable 也 returns 在您的 Excel 文件中隐藏了 table:通常像 Sheet1$_ 这样的名称表示创建了一个隐藏的 table当您在 Sheet1$.

上应用过滤器时

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

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

另请注意,您需要执行此操作才能读取具有多行标题的 excel 文件:

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

例如:

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]