tags:

views:

49

answers:

1

This is my first attempt to read an Excel 2007 file via ADO.net, and I must be missing something b/c when I try to run the query, I get an exception. When I started looking, it's b/c the table (worksheet) isn't there. Can someone please tell me what I'm doing wrong?

Here is my code:

        string cs = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=My File.xlsx;Extended Properties=""Excel 12.0;IMEX=1;""";

        using (OleDbConnection con = new OleDbConnection(cs))
        {

            con.Open();

            string query = "SELECT * FROM [Sheet1$]";

            OleDbCommand cmd = new OleDbCommand(query, con); 

            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);

            DataTable dt = new DataTable();

            DataTable worksheets = con.GetSchema("Tables");


            adapter.Fill(dt);
            .
            .
            .
         }
+1  A: 

Take a look at the accepted answer here

http://stackoverflow.com/questions/1328579/the-first-column-of-the-excel-file-to-put-in-string-variable-c

It works for Excel 2003 but I think it could easily be adapted to work with 2007.

JayG
There's actually not much of a difference between what I have and that solution. I changed to see if it worked, and it still doesn't. The issue is that for some reason the worksheet(s) aren't being found.
mjmcinto
This is a guess, but is the space in the Excel file name in the connection string causing the problem?
JayG
The space in the file name was the issue. Thanks so much...I should have checked that, but just over looked it.
mjmcinto
I'll just add that I have run into the same issue where the exception was saying something about worksheet object not being found, while the truth was that I misspelled the file name. The error message is not helpfull, well it is even misleading!
Piotr Owsiak