[英]Error reading from Excel in C#: “…could not find the object…”
I have more or less exactly the same error as in this post , but that solution has not solved my problem. 我或多或少与这篇文章中的错误完全相同,但是该解决方案无法解决我的问题。
The error message I get: 我收到的错误消息:
The Microsoft Office Access database engine could not find the object 'Adresser$'. Make sure the object exists and that you spell its name and the path name correctly.
I have checked and double-checked that the name is right, I have renamed the sheet and copy-pasted the name into my code, but nothing seems to work. 我检查并仔细检查了名称是否正确,我已重命名工作表并将名称复制粘贴到我的代码中,但似乎没有任何效果。 What am i doing wrong?
我究竟做错了什么?
This is my code: 这是我的代码:
string conStr = String.Format(
@"Provider={0};Data Source=""{1}"";Extended Properties=""{2}""",
"Microsoft.ACE.OLEDB.12.0",
"REGISTER 090310.xls",
"Excel 12.0 Xml;IMEX=1;HDR=YES;");
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
using (IDbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = conStr;
using (IDbCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT TOP 10 * FROM [Adresser$]";
connection.Open();
// The exception is thrown on this line, with yellow highlight on
// IDataReader dr = command.ExecuteReader()
using (IDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
Console.WriteLine(
string.Format("First name: {0}\tLast name: {1}",
dr[0].ToString(),
dr[1].ToString()));
}
}
}
}
OK, I solved it: 好的,我解决了:
It turns out, this provider was able to connect correctly to an Excel 2003 worksheet, but couldn't read it. 事实证明,此提供程序能够正确连接到Excel 2003工作表,但无法读取它。 Thus, I opened the worksheet in Excel 2007 and re-saved it in the
.xlsx
format , and changed my connection string accordingly. 因此,我在Excel 2007中打开了工作表,并以
.xlsx
格式重新保存了该工作表 ,并相应地更改了我的连接字符串。 It all works now =) 现在一切正常=)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.