Home » excel » excel – OleDbConnection in C#

excel – OleDbConnection in C#

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have written code for inserting data into excel sheet.My code doesn’t throw any exception and each time excel file’s size get incremented by 1KB. But when I open the sheet it does not show any data.

I am puzzled and unable to figure out the problem.
Please help and thanx in advance…!!!

string strSQL = string.Empty;
excelConn.Open();
strSQL = "INSERT INTO [" + sheetName + "$]  ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11]) VALUES(@value1, @value2, @value3, @value4, @value5,@value6, @value7, @value8, @value9 ,@value10, @value11)";
excelCommand = new OleDbCommand(strSQL, excelConn);
excelCommand.Parameters.AddWithValue("@value1", Program);
excelCommand.Parameters.AddWithValue("@value2", District);
excelCommand.Parameters.AddWithValue("@value3", Period);
excelCommand.Parameters.AddWithValue("@value4", paramValue1);
excelCommand.Parameters.AddWithValue("@value5", paramValue2);
excelCommand.Parameters.AddWithValue("@value6", paramValue3);
excelCommand.Parameters.AddWithValue("@value7", BusinessLogic);
excelCommand.Parameters.AddWithValue("@value8", ExpectedResult);
excelCommand.Parameters.AddWithValue("@value9", ActualResult);
excelCommand.Parameters.AddWithValue("@value10", Status);
excelCommand.Parameters.AddWithValue("@value11", DateTime);               

excelCommand.ExecuteNonQuery();
return true;
How to&Answers:

OLEDB requires that parameters should not be named. You should be using Question Marks in your query:

strSQL = "INSERT INTO [" + sheetName + "$]  
         ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11]) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";