3

I want to read excell file with this code:

var fileName = @"d:\1.xlsx"; 
var connectionString = string.Format(
    "Provider=Microsoft.Jet.OLEDB.4.0; data source="+fileName+
    "; Extended Properties=Excel 8.0;", fileName);

var adapter = new OleDbDataAdapter("SELECT * FROM [sheet1$]", connectionString);
var ds = new DataSet();

adapter.Fill(ds, "anyNameHere");

DataTable data = ds.Tables["anyNameHere"];

But when run the program I get this error:

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll

Additional information: External table is not in the expected format.

How can i solve that?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
elnaz irani
  • 277
  • 1
  • 3
  • 11

4 Answers4

3

Your excel file is 2007 version, *.xlsx and you are using the wrong provider(Microsoft.Jet.OLEDB.4.0).

Try this approach:

var fileName = @"d:\1.xlsx"; 
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;";
Thanos Markou
  • 2,587
  • 3
  • 25
  • 32
0

Its already answer the question in the past post Please follow the below link

Answer link

The answer is very simple

sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Test.xlsx;Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"";
Community
  • 1
  • 1
Abhilash Thomas
  • 833
  • 2
  • 12
  • 23
0

you have diff version of Excel file, get the file name, if its extension is .xlsx, use this

var fileName = @"d:\1.xlsx"; 
var connectionString = string.Format(
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="{0}";Extended Properties=Excel 12.0;", fileName);
BrainCoder
  • 5,197
  • 5
  • 30
  • 33
0

I would suggest this Libary called FileHelpers. Since discovering it i have never written the plumbing code myself. It lets you concentrate on the actual business logic.

bhupendra patel
  • 3,139
  • 1
  • 25
  • 29