Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to read an Excel (.xlsx) file using the code shown below.Error is.... External table is not in the expected format.

What I have tried:

C#
DataTable dtData = new DataTable();
        OleDbConnection oOleDbConnection;
        OleDbDataAdapter oOleDbDataAdapter;
        try
        {
            oOleDbConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0';");
            oOleDbDataAdapter = new OleDbDataAdapter("select * from [sheet1$]", oOleDbConnection);
            oOleDbDataAdapter.Fill(dtData);
            oOleDbConnection.Close();
            oOleDbConnection.Dispose();
            return dtData;
        }
        catch (Exception ex)
        {
            return null;
        }




Can you please tell me where I went wrong..
Posted
Updated 25-Jul-21 12:40pm
v2
Comments
Maciej Los 13-Jun-18 8:15am    
1. Seems, you forgot to open connection.
2. How do you create and initiate path variable?
anuj___chauhan 13-Jun-18 13:08pm    
same code working with .xls format but not working with .xlsx
[no name] 13-Jun-18 14:37pm    
Then it's the format or the provider / driver; and not the code.

 
Share this answer
 
Please, read my comment first.

1. You forgot to open connection:
C#
oOleDbConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0';");
oOleDbConnection.Open(); //you missed that!
oOleDbDataAdapter = new OleDbDataAdapter("select * from [sheet1$]", oOleDbConnection);


2. A path variable should be initiated this way:
C#
string path = @"C:\Folder1\Foder2\FileName.xlsx";
//or - without @
//note: single [\] is an escape character, so you need to pass two [\\] to change its meaning
string path = "C:\\Folder1\\Foder2\\FileName.xlsx";


3. Check if sheet1 exists in a collection of sheets!

4. Use specific connection string for each Excel file (depending on extension):
See: Microsoft ACE OLEDB 12.0 Connection Strings - ConnectionStrings.com[^]
For xlsx files:
C#
string constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml';", path);
 
Share this answer
 
In my case I fotgoted to close the oOleDbConnection. oOleDbConnection.Close(); In background was an Excel with the opened file, I had to kill te process and reopened visual Studio.
 
Share this answer
 
Comments
CHill60 26-Jul-21 5:01am    
That's an unusual message to get when the file is already open. I suggest you check the other solutions because there is more going on than having just left the file already open

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900