使用c#和oledb插入到excel命令时包围无效?

时间:2012-09-19 17:06:27

标签: c# excel oledb

我正在使用OLEDB 删除某些记录到Excel文件

    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();
            }

我的excel文件有一个名为D.M.的列。这导致了这个错误。我想在excel中保留这个列名,因为它被另一个软件使用。 C#代码中是否有任何解决方法可以插入以应对此问题?

enter image description here

1 个答案:

答案 0 :(得分:1)

我发现问题的地方是此行中的关键字values

OleDbCommand cmdInsert = new OleDbCommand("insert into [sd$] values" +

INSERT语句中,您通常在调用VALUES之前指定列字段。或者,您可以在不命名列字段的情况下调用VALUES。在这种情况下,你做两件事。高于VALUES在分配列之前会导致问题。

一个选项是完全删除列声明,然后执行insert into [sd$] values "(" + "'" + rec.SampleNo + - 即列和条目匹配。您还可以尝试将INSERT语句中的列重命名为[DM],然后在插入数据后将excel电子表格中的列重命名为[DM]作为例程任务,使用以下代码修改它当然:{{3} }

如果其他所有方法都失败,请使用http://dontbreakthebuild.com/2012/03/16/reading-excel-column-names-in-c-using-excel-interop/来尝试操作文档。

我出去了!祝你好运。