无法弄清楚为什么我得到Excel文件的System.Data.OleDb.OleDbException

时间:2011-12-12 14:25:41

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

    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'。   确保对象存在,并拼写其名称和路径   名字正确。行

2 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:0)

只是一个想法:当我在一个选择了64位平台目标的项目中使用它们时,我在Excel驱动程序中有oledb异常。尝试将项目设置和更改平台目标更改为x86。