【问题标题】:can't figure out why Im getting System.Data.OleDb.OleDbException for Excel file无法弄清楚为什么我会为 Excel 文件获取 System.Data.OleDb.OleDbException
【发布时间】:2023-04-03 19:50:01
【问题描述】:
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*";
    openFileDialog1.FilterIndex = 2;
    openFileDialog1.RestoreDirectory = true;

    // Show the dialog and get result.
    DialogResult result = openFileDialog1.ShowDialog();
    if (result == DialogResult.OK) // Test result.
    {
        labelFilePath.Text = openFileDialog1.FileName;
        string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + labelFilePath.Text.Trim() + ";Extended Properties=\"Excel 8.0;HDR=YES\"";
        using (var conn = new System.Data.OleDb.OleDbConnection(connString)) 
        { 
            conn.Open(); 
            try
            {
                using (OleDbCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "Select * From [Sheet1]";
                    using (OleDbDataReader reader = cmd.ExecuteReader())
                    {
                        int firstNameOrdinal = reader.GetOrdinal("First Name");
                        int lastNameOrdinal = reader.GetOrdinal("Last Name");
                        while (reader.Read())
                        {
                            Console.WriteLine("First Name: {0}, Last Name: {1}", reader.GetString(firstNameOrdinal), reader.GetString(lastNameOrdinal));
                        }
                    }
                }
            }
            catch (OleDbException odbe)
            {
                Console.WriteLine(odbe.Errors.ToString());
                Console.WriteLine(odbe.Message.ToString());
            }
        } 

    }
    Console.WriteLine(result); // <-- For debugging use only.

}

我在OleDbDataReader reader = cmd.ExecuteReader() 收到错误

这是输出

“System.Data.OleDb.OleDbException”类型的第一次机会异常 发生在 System.Data.dll System.Data.OleDb.OleDbErrorCollection 中 Microsoft Jet 数据库引擎找不到对象“Sheet1”。 确保对象存在并且拼写它的名称和路径 正确命名。好的

【问题讨论】:

  • 我们可以查看异常详情吗?
  • 您需要显示 OleDbException.Message 属性,可能还有 innerException(它是 Message 属性)。
  • 文件是否已在 excel 实例或其他数据库连接(即 SSMS)中打开??
  • 我没有打开文件。 Excel 已关闭。

标签: c# .net excel c#-4.0 oledb


【解决方案1】:

尝试更改以下行(注意 $):

cmd.CommandText = "Select * From [Sheet1$]";

在这种情况下,您将选择工作表中的所有内容,但是此表示法扩展到选择命名范围,如下所示:

cmd.CommandText = "Select * From [Sheet1$NamedRange]";

【讨论】:

    【解决方案2】:

    只是一个想法:当我在选择了 64 位平台目标的项目中使用 Excel 驱动程序时,我在 Excel 驱动程序中遇到了 oledb 异常。尝试转到项目设置并将构建选项卡上的平台目标更改为 x86。

    【讨论】:

    • 不,你之前在 connection.Open() 中抛出的异常。但是在 cmd.ExecuteReader() 成功 connection.Open() 后抛出了这个异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多