Home » excel » Inserting a row into Excel Spreadsheet via C# and OleDb

Inserting a row into Excel Spreadsheet via C# and OleDb

Posted by: admin April 23, 2020 Leave a comment

Questions:

I need to programmatically insert a row into an Excel Spreadsheet multiple times. I need to actually insert a new row and not insert data, that is, I need to actually shift all other rows down by one.

I am currently using OleDB to insert the data itself like so:

//Note I have missed some code out for simplicities sake, this all works fine however
OleDbConnection oledbConn = null;

OleDbCommand cmd = null;

OleDbConnection = new OleDbConnection(connString);           
OleDbConnection.Open();

string connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0; \"", TargetFile);

sting InsertCommand = string.Format("INSERT INTO [{0}:{1}] Values({2})", WorksheetName, Coord, valuestring);

cmd = new OleDbCommand(InsertCommand, oledbConn);

cmd.ExecuteNonQuery();

//close etc

I want to be able to insert a row in a similar fashion. Is this possible?

How to&Answers:

At a glance, you need to specify read write, the default is read only. Perhaps:
“Provider=Microsoft.Jet.OLEDB.4.0;” & _
“Data Source=C:\Docs\Test.xls;” & _
“Mode=ReadWrite;Extended Properties=””Excel 8.0;HDR=No”””

At a second glance and re comments, I think Interop might be the best bet.

Answer:

ipavlic is right, you will be better off using an external third-party library for this. There are several available. OfficeWriter is one example:

http://www.officewriter.com

Once you open a workbook with OfficeWriter, you can use this method on the Worksheet class to insert rows. It mimics Excel’s behavior, including updating/stretching formulas and other updates:

public void InsertRows(int rowNumber, int rowCount)