Skip to main content
 首页 » 编程设计

c#之使用 C# 读取 Excel 文件导致抛出 OleDbException

2024年02月13日11TianFang

消息说

The Microsoft Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet1$' is not a local object, check your network connection or contact the server administrator.

Worksheet中工作表的名称是“Sheet1”

        string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES"";", fileName); 
        string query = String.Format("SELECT [columnName1],[columnName2],[columnName3] from [{0}]", "Sheet1$"); 
        OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString); 
        DataSet dataSet = new DataSet(); 
        dataAdapter.Fill(dataSet); 
        DataTable YourTable = dataSet.Tables[0]; 
        listBox1.DataSource = YourTable.Columns["ColumnName1"]; 

请您参考如下方法:

这对我有用:

string filename = @"C:\Book1.xlsm"; 
 
        string connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\";", filename); 
        string query = String.Format("SELECT * from [{0}$]", "Sheet1"); 
        OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString); 
        DataSet dataSet = new DataSet(); 
        dataAdapter.Fill(dataSet); 
        DataTable YourTable = dataSet.Tables[0]; 

*注意:*如果您的数据没有 header ,则HDR=NO

还注意到在你的问题中你使用了

[columnName1],[columnName2],[columnName3] 

供您选择的列。请记住,这些应该是您想要获取的列中第一个单元格的值。

要获取 E 列,请使用:

        string connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=NO\";", filename); 
        string query = String.Format("SELECT [F5] from [{0}$]", "Sheet1"); 

将 5 替换为您需要的任何其他列号

F1 = A 
F2 = B 
F3 = C  

等等。

您遇到的错误可能是因为您打开并激活了文件。

或者您指向错误的文件(请记住,您必须在 filename 字符串中包含完整的文件路径。并确保工作表是正确的。请注意我包含的事实$ 在我的字符串中,而不是在我的参数中,因此请记住只输入您要获取的工作表的名称。如果您仍然无法向我提供工作表的完整文件名,那么您使用即 C:\Book1.xlsm 和您尝试从中获取数据的工作表。