简体   繁体   中英

Inserting a row into Excel Spreadsheet via C# and OleDb

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}:{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?

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.

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)

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