0

我正在使用 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 文件有一个名为 DM 的列,它导致了这个错误。我想将此列名保留在 excel 中,因为它被另一个软件使用。在 C# 代码中是否有任何解决方法可以解决这个问题?

在此处输入图像描述

4

1 回答 1

1

我看到问题的地方是values这一行中的关键字

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

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

一种选择是完全删除列声明并直接执行insert into [sd$] values "(" + "'" + rec.SampleNo +- 即列和条目匹配。您也可以尝试将 INSERT 语句中的列重命名为 [DM],然后在插入数据后将 excel 电子表格中的列重命名为 [DM] 作为常规任务,当然使用以下代码对其进行修改:http:// dontbreakthebuild.com/2012/03/16/reading-excel-column-names-in-c-using-excel-interop/

如果一切都失败了,请使用Open XML SDK 2.0来尝试和操作文档。

我出去了!祝你好运。

于 2012-09-19T17:23:23.600 回答