I am running into an error when trying to insert into an Excel worksheet
This is the layout of my Excel worksheet named Sheet1:
id name
1 test
2 apple
3 pear
I want to insert this data into the Excel worksheet:
4 pineapple
This is my code below:
try{
string srcExcel = "C:\\Users\\Desktop\\insertTest.xlsx";
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + srcExcel + "; Extended Properties = 'Excel 8.0;HDR=Yes;IMEX=1'");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert Into [Sheet1$] (id,name) Values('4','pineapple')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MessageBox.Show("Insert Success!");
MyConnection.Close();
}
catch (Exception eInnerData)
{
MessageBox.Show("Method: getInnerData " + eInnerData.ToString());
}
After running this code an exception is thrown and caught with this error message:
Operation must use an updateable query
I am using Microsoft Excel 2010
Remove the IMEX=1 from the connectionstring. Also make sure the file is not readonly and not currently open in Excel
For what it's worth, I recommend reading and writing the xlsx file with something like the EPPlus library, rather than the Access db driver