Worksheets to DataSet
Jun 28, 2016 at 2:48am UTC
Hello,
I'm having trouble reading and storing worksheets into a dataset. This is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
DataSet^ ds = gcnew DataSet();
String^ ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\test.xlsx;Extended Properties=\"Excel 12.0 XML;HDR=YES\"" ;
for (int i = 1; i<21; i++)
{
DataTable^ dt= gcnew DataTable();
OleDbConnection^ conn = gcnew OleDbConnection(ConnectionString);
OleDbCommand^ com = gcnew OleDbCommand();
com->Connection = conn;
com->CommandText = "select * from [Week " + i.ToString() + "]" ;
OleDbDataAdapter^ adap = gcnew OleDbDataAdapter();
adapt->SelectCommand = com;
adapt->Fill(dt);
ds->Tables->Add(dt);
ds->Tables[i-1]->TableName = "Week " + i.ToString() + ";
conn->Close();
}
Each Worksheet is labelled Week 1 to Week 20. I would like all worksheets to be loaded into the dataset. I was hoping that I could just do a simple loop but the only table that gets read and placed into the dataset is the first worksheet, Week 1.
No doubt it's something simple.
Any suggestions would be great!
Jun 28, 2016 at 4:34am UTC
It appears that I've solved my own problem... The line:
com->CommandText = "select * from [Week " + i.ToString() + "]" ;
needs to be:
com->CommandText = "select * from [Week" + i.ToString() + "$]" ;
Cheers,
Topic archived. No new replies allowed.