简体   繁体   中英

How to insert a new Row in Excel sheet using Microsoft.Ace.Oledb in VS 2012 using c#

I'm doing the following to insert a row in an excel sheet using Microsoft.ACE.OLEDB as a provider in c# code: 1- I have the following connection string:

string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=test.xlsx;Mode=ReadWrite;ReadOnly=False;Extended Properties=""Excel 12.0 Xml;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text;HDR=YES""");

2- And the following code to insert:

        string strSQL = "INSERT INTO [sheet1$] (Id, Name, parentId) VALUES(196,'test',1)";
        OleDbConnection excelConnection = new OleDbConnection(connectionString);
        excelConnection.Open(); 
        OleDbCommand dbCommand = new OleDbCommand(strSQL, excelConnection);
        dbCommand.ExecuteNonQuery();
        dbCommand.Dispose();
        excelConnection.Close();
        excelConnection.Dispose();

But once I run my code i have the following OleDbException exception, when opening the connection:

Could not find installable ISAM

I did my search and found that it's related to a bad connection string format, so after several try i found that when i removed "ReadOnly=False;" from the connection string the OleDbException exception changed to:

Operation must use an updateable query

When executing the command "dbCommand.ExecuteNonQuery"; so i also did my search and found that it's a permission issue so i gave the Excel file a total permission to be modified by the user group "Everyone", but still have the same exception. I'm really lost here, i tried so many things and i would appreciate any help; i'm pretty sure it's a silly mistake!

I did a test with your code: it seems to work if your remove the 'Mode=ReadWrite;ReadOnly=False;' of the connection string.

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