Inserting a row into Excel Spreadsheet via C# and OleDb

一个人想着一个人 提交于 2020-01-04 02:27:08

问题


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?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/8944187/inserting-a-row-into-excel-spreadsheet-via-c-sharp-and-oledb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!