运行INSERT命令时的奇怪行为(C#和XLSX)

运行INSERT命令时的奇怪行为(C#和XLSX),c#,sql,excel,insert,C#,Sql,Excel,Insert,不知何故,我无法理解我正在使用的命令发生了什么。 基本上,我希望将数据插入EXCEL文件,如下所示: string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=scriptsdb.xlsx;Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\""; OleDbConnection objConn = new OleDbConnection(Conn

不知何故,我无法理解我正在使用的命令发生了什么。 基本上,我希望将数据插入EXCEL文件,如下所示:

string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=scriptsdb.xlsx;Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\"";
OleDbConnection objConn = new OleDbConnection(ConnectionString);
string sSQLQuery = "INSERT INTO [Plan1$] ([ID], [NAME], [DESCRIPTION], [SQL_CODE]) VALUES ('" + NextID + "','" + txtbxName.Text + "','" + txtbxDescription.Text + "','" + txtboxSQL.Text + "')";
OleDbCommand cmd = new OleDbCommand(sSQLQuery, objConn);
objConn.Open();
cmd.ExecuteNonQuery();
现在看看。有时它会工作(添加记录),有时我会收到错误消息(操作必须使用可更新的查询)

虽然听起来很奇怪,但当文本字段只有一个单词时,我却收到了错误消息。e、 g:“测试”。只要我把它改成“测试一”,它就可以正常工作。如果我试着从一开始就用两个词来保存它,它就会起作用

知道我做错了什么吗


谢谢

注意:将插入[Plan1$]更改为插入[Sheet1$]

工作代码

class Program
        {
            static void Main(string[] args)
            {
            string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+"C:\\Users\\123\\Desktop\\plan1.xlsx;"+"Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes\";";
            // here you can use your text box or from
            // where ever you access the data to be inserted
            // into the that Excel file sheet

            string selectString = "INSERT INTO [Sheet1$] ([ID], [NAME], [DESCRIPTION], [SQL_CODE]) VALUES ('1','maziz','Not working','selectfrom you')";

            OleDbConnection con = new OleDbConnection(connectionString);
            OleDbCommand cmd = new OleDbCommand(selectString, con);

            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                Console.WriteLine("Successfully inserted the records");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
               con.Close();
               con.Dispose();
            }
            Console.ReadLine();
            }
        }

修改excel文件所在文件夹的权限。请检查答案,希望它能帮助您。