尝试INSERT INTO excel文件时遇到错误

时间:2014-07-31 14:39:50

标签: c# sql excel

我试图弄清楚如何将一行数据插入现有的Excel文件中。该文件很简单,只有3个标题,CITY STATE和ZIP。我已经在Excel中选择了3个单元格并将其命名为Browns。当我运行程序时,我得到一个错误代码。查询值和目标字段的数量不同。

这是我传递给方法

的内容
Excel_IO.inSertRowTEST(filePath1.Text, "Browns");

我创建的方法。

public static void inSertRowTEST(string FP1, string TableName)
    {
        string sql = null;
        Excel_IO.openSheet(FP1);
        sql = "INSERT INTO  " + TableName + " VALUES ('Jack','Smith')";
        myCommand.CommandText = sql;
        myCommand.ExecuteNonQuery();
        Excel_IO.closeMyConnection();


    }

public static void openSheet(string filePathMain)
    {
        // MyConnection Equals A New OleDbConnection, The Connection Defines Which Versions Of Excel Files Can Be Used, The file path, And Some Basic Excel Properties
        MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ace.OLEDB.12.0;Data Source=" + filePathMain + ";Extended Properties=\"Excel 8.0; HDR=Yes;\";");

        // Opening The Connection With The Excel File
        MyConnection.Open();

        // The Connection Gets MyConnection
        myCommand.Connection = MyConnection;


    }

public static void closeMyConnection()
    {
        MyConnection.Close();

    }

有人有任何建议吗?

完全错误代码


System.Data.OleDb.OleDbException(0x80004005):查询值和目标字段的数量不同。

at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)

at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams,Object& executeResult)

at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)

at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior,Object& executeResult)

at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior,String method)

at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()

位于c:\ Users \ t1008ts \ Desktop \ Projects \ MasterP2 \ May19Template \ Excel_IO.cs中的MyExcel_IO.Excel_IO.inSertRowTEST(String FP1,String TableName):第220行

at myExcel_IO.Form1.button1_Click(Object sender,EventArgs e)位于c:\ Users \ t1008ts \ Desktop \ Projects \ MasterP2 \ May19Template \ Form1.cs:第121行

确定

1 个答案:

答案 0 :(得分:0)

  

我已在Excel中选择了3个单元格,并将范围命名为Browns

我认为当您插入Excel电子表格时,您需要指定表格(或工作表),而不是创建范围。

尝试将工作表重命名为" Browns"

http://office.microsoft.com/en-us/excel-help/rename-a-sheet-HP005202108.aspx

相关问题