我的插入语句不适用于 C# 中的 Excel

My Insert Statement Isn't working for Excel in C#

嘿,我的插入语句不起作用 我使用相同的代码将其他面板数据插入 excel sheet 它在那里工作得很好,但是当我尝试将数据插入其他 sheet 使用第二个面板它抛出异常 "Insert INTO Statement is not valid" 我检查了其中的每一件事我找不到任何错误。我正在使用 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());
            }
        }

您似乎在为列 Password 使用保留名称。你需要用 []:

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