Search code examples
c#exceloledb

How to get the data from Excel into C#?


I have a C# program that takes some data from Excel and saves it to an SQL database. When I open the Excel file and run the program it is working successfully but if I close the Excel file and try to run the program again there is an error like:

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll and Additional information=The table is not true way.

So how can I solve this problem?

Here is the part of my code that errors:

string conexcel = "Provider=Microsoft.Jet.OleDB.4.0;" + "Data Source=\kisiler.xlsx;" + "Extended Properties=Excel 8.0";

string cmd = "SELECT * FROM [Sayfa1$]";
OleDbDataAdapter adp = new OleDbDataAdapter(cmd, conexcel);
DataSet ds = new DataSet();
adp.Fill(ds);

adp.Fill(ds); is my error part.


Solution

  • What you are trying to do is opening an xlsx file, but using an older version of oledb provider. Try this:

    "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=kisiler.xlsx;" + "Extended Properties=Excel 12.0 Xml";