首页 > 解决方案 > 我的插入语句不适用于 C# 中的 Excel

问题描述

嘿,我的插入语句不起作用我使用相同的代码将其他面板数据插入到 excel 工作表中,它在那里工作得很好,但是当我尝试使用第二个面板在其他工作表中插入数据时,它抛出异常“插入 INTO 语句无效“我检查了其中的每一件事,我找不到任何错误。我正在使用 OleDb 进行插入。这是我用于第一个面板插入的相同代码。

 private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                String filename1 = @"E:DB\TestDB.xlsx";
                String connection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename1 + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
                OleDbConnection con = new OleDbConnection(connection);
                con.Open();
                int id = 4;
                string user = txtMUserName.Text.ToString();
                string pass = txtMPassword.Text.ToString();
                string role = txtMRole.Text.ToString();
                DateTime date = DateTime.Now;
                string Date = date.ToString("dd/MM/yyyy");
                //string Time = date.ToLongTimeString();
                string Time = "3:00 AM";
                String Command = "Insert into [Test$] (UserID, UserName, Password, Role, Created_Date,Created_Time) VALUES ('"
                        + id.ToString() + "','"
                        + user + "','"
                        + pass + "','"
                        + role + "','"
                        + Date + "','"
                        + Time + "')";
                OleDbCommand cmd = new OleDbCommand(Command, con);
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Success!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

标签: c#excelwinformsoledbexception

解决方案


好像您正在为 column 使用保留名称Password。你需要逃避它[]

string Command = "Insert into [Test$] (UserID, UserName, [Password], Role, Created_Date,Created_Time) VALUES ('"
                        + id.ToString() + "','"
                        + user + "','"
                        + pass + "','"
                        + role + "','"
                        + Date + "','"
                        + Time + "')";

推荐阅读