I am iserting some records to excel file using OLEDB
foreach (TblSample rec in LstTblSample)
{
OleDbCommand cmdInsert = new OleDbCommand("insert into [sd$]" +
"([Lab Ref],[D.M.],PH,CP,ADF,NDF,DMD,ME,NIRASH,IFCOW,IFSHEEP,NH3,UFV,UFL,PDIE,PDIN,PDIA,LFU,CFU,SFU) values" +
"(" + "'" + rec.SampleNo + "'" + "," + "'" + rec.DryMatter + "'" + "," + "'" + rec.pH + "'" + "," +
"'" + rec.CrudeProtein + "'" + "," + "'" + "" + "'" + "," + "'" + rec.NDF + "'" + "," + "'" + rec.DMD + "'" + "," +
"'" + rec.ME + "'" + "," + "'" + rec.ASH + "'" + "," + "'" + rec.DMIntakeCattle + "'" + "," +
"'" + rec.DMIntakeSheep + "'" + "," + "'" + rec.NH3 + "'" + "," + "'" + rec.UFV + "'" + "," +
"'" + rec.UFL + "'" + "," + "'" + rec.PDIE + "'" + "," + "'" + rec.PDIN + "'" + "," + "'" + rec.PDIA + "'" + "," +
"'" + rec.LFU + "'" + "," + "'" + rec.CFU + "'" + "," + "'" + rec.SFU + "'" + ")", con);
cmdInsert.ExecuteNonQuery();
}
My excel file has a column named D.M. which is causing this error. I want to keep this column name in excel because, its used by another software. Is there any work around in C# code for insert to cope with this?
Where I see a problem is the keyword values
in this line
OleDbCommand cmdInsert = new OleDbCommand("insert into [sd$] values" +
In the INSERT
statement you usually specify the column fields before calling VALUES
. Alternatively you can call VALUES
without naming the column fields. In this instance you do both. Above VALUES
BEFORE assigning the columns causes a problem.
One option is to remove the column declaration completely and just do insert into [sd$] values "(" + "'" + rec.SampleNo +
- i.e. is the columns and entries match. You can also try rename the column in the INSERT statement to [DM] and then after the data was inserted rename the column in the excel spreadsheet to [D.M.] as a routine task using the following code modifying it of course: http://dontbreakthebuild.com/2012/03/16/reading-excel-column-names-in-c-using-excel-interop/
If all else fails make use of the Open XML SDK 2.0 to try and manipulate the document.
I'm out! Good luck.