简体   繁体   中英

Getting Oledb exception when updating column in excel

I am getting the following error "No value given for one or more required parameters." On the ExceuteNonQuery() line of the below code.

        System.Data.OleDb.OleDbConnection finalConnection;
        System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
        string sql = null;
        finalConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source ='c:\\temp\\test.xlsx'; Extended Properties ='Excel 12.0 Xml;HDR=NO';");
        finalConnection.Open();
        myCommand.Connection = finalConnection;
        foreach (VinObject v in VinList)
            {
            sql = "Update [Sheet1$] set O = ? where S = ?;";
            myCommand.Parameters.Add(new OleDbParameter("@amt", v.CostNewAmt));
            myCommand.Parameters.Add(new OleDbParameter("@vin", v.VIN));
            myCommand.CommandText = sql;
            myCommand.ExecuteNonQuery();
            }
        finalConnection.Close();

I have also tried using a separate command each time, same error.

    foreach (VinObject v in VinList)
            {
            using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source ='c:\\temp\\test.xlsx'; Extended Properties ='Excel 12.0 Xml;HDR=No';"))
                {
                con.Open();
                string query = @"UPDATE [Sheet1$] SET O = ? WHERE S = ?";
                OleDbCommand cmd = new OleDbCommand(query, con);
                cmd.Parameters.AddWithValue("@param1", v.CostNewAmt);
                cmd.Parameters.AddWithValue("@param2", v.VIN);
                cmd.ExecuteNonQuery();
                con.Close();
                }
            }

I am able to modify that into an insert and insert into a new excel spreadsheet, but for the life of me cannot get this update to work. Any idea what I am doing wrong? Thanks for the help.

You're getting the error because Excel doesn't recognize the column letter aliases "O" and "S". It needs the actual column "name", which is the value of the cell in the first populated row. If there is not a valid value in that cell, or you have specified HDR=NO in your connection string, the columns will be named F1 , F2 ... Fn . If you're not sure what the inferred column names are, examine the names using OleDbConnection.GetSchema(String,String[]) or OleDbDataReader.GetName(Int32) .

Since you have specified HDR=NO in your connection string, your correct SQL will likely be

"Update [Sheet1$] set F15 = ? where F19 = ?;"

For future reference, check out:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM