Home » excel » Error reading from Excel in C#: "…could not find the object…"

Error reading from Excel in C#: "…could not find the object…"

Posted by: admin May 14, 2020 Leave a comment

Questions:

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()));
            }
        }
    }
}
How to&Answers:

OK, I solved it:

It turns out, this provider was able to connect correctly to an Excel 2003 worksheet, but couldn’t read it. Thus, I opened the worksheet in Excel 2007 and re-saved it in the .xlsx format, and changed my connection string accordingly. It all works now =)