I've searched internet for this and couldn't really find a question like it. Everyone was looking for a way to import an individual sheet in the excel file but what I want is to import all the sheets in the file to DataTable
's in DataSet
without knowing the sheet names.
I've not done much things with Excel before. This a sample and partially working code I've found on the internet and it only parses the given sheet name:
public static DataSet Parse(string fileName, string workSheetName)
{
string connectionString = string.Format("provider=Microsoft.Jet.OLEDB.4.0; data source={0};Extended Properties=Excel 8.0;", fileName);
string query = string.Format("SELECT * FROM [{0}$]", workSheetName);
DataSet data = new DataSet();
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(data);
}
return data;
}
In the code above, as you see, workSheetName should be passed in so the query can know where to look at to import. In my case, I want it to traverse all the sheets no matter what they are named like and import them to individual DataTable
's of a DataSet
.
So in essence, the final thing will be a DataSet
in which each DataTable
holds rows for each sheet in the imported file.
The function that was suggested by Avitus is correct but it has logica error, you must rewrite in :
this is correct, otherwise you must dispose connection and dataadapter manually.
This might not be the best and the fastest one, but its another way (Edit- added elimination of blank cells):
Because I was bored:
This is a code I came up with and it works perfect but I saw someone else already added an answer: