【问题标题】:The Microsoft Jet database engine could not find the object 'Sheet1$_'Microsoft Jet 数据库引擎找不到对象“Sheet1$_”
【发布时间】:2015-11-17 13:13:45
【问题描述】:

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

Microsoft Jet 数据库引擎找不到对象“Sheet1$_”。确保对象存在并且正确拼写其名称和路径名。

我的 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 等内的所有列。

【问题讨论】:

    标签: c# sql excel oledb


    【解决方案1】:

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

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

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

    另请注意,您需要这样做才能读取具有多行标题的 excel 文件:

    • 在连接字符串的EXTENDED PROPERTIES 中设置HDR=No
    • 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]
    

    【讨论】:

    • 是的,我将其更改为 sheet1$,但我没有得到列名:“Shifts”、“15Min”等。我必须在每天的数据表中获取这些
    • 这是一个完全不同的问题,但是......答案已更新! ;)
    猜你喜欢
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多