不知道为什么我得到Excel文件的System.Data.OleDb.OleDbException

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.dll System.Data.OleDb.OleDbErrorCollection中发生types'System.Data.OleDb.OleDbException'的第一次机会exceptionMicrosoft Jet数据库引擎找不到对象'Sheet1'。 确保对象存在,并且正确拼写其名称和path名称。 好

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

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

在这种情况下,您正在select表格中的所有内容,但是这种表示法可以扩展为select命名范围,如下所示:

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

只是一个念头:当我在一个select64位平台目标的项目中使用它们时,我在Excel驱动程序中出现了oledbexception。 尝试进行项目设置并将“生成”选项卡上的平台目标更改为x86。