简体   繁体   English

通过C#和OleDb在Excel电子表格中插入一行

[英]Inserting a row into Excel Spreadsheet via C# and OleDb

I need to programmatically insert a row into an Excel Spreadsheet multiple times. 我需要以编程方式多次向Excel电子表格中插入一行。 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: 我目前正在使用OleDB来插入数据本身:

//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;" 也许:“Provider = Microsoft.Jet.OLEDB.4.0;” & _ "Data Source=C:\\Docs\\Test.xls;" &_“数据源= C:\\ Docs \\ Test.xls;” & _ "Mode=ReadWrite;Extended Properties=""Excel 8.0;HDR=No""" &_“Mode = ReadWrite; Extended Properties =”“Excel 8.0; HDR = No”“”

At a second glance and re comments, I think Interop might be the best bet. 乍一看并重新评论,我认为Interop可能是最好的选择。

ipavlic is right, you will be better off using an external third-party library for this. ipavlic是对的,你最好使用外部第三方库。 There are several available. 有几个可用。 OfficeWriter is one example: OfficeWriter就是一个例子:

http://www.officewriter.com http://www.officewriter.com

Once you open a workbook with OfficeWriter, you can use this method on the Worksheet class to insert rows. 使用OfficeWriter打开工作簿后,可以在Worksheet类上使用此方法来插入行。 It mimics Excel's behavior, including updating/stretching formulas and other updates: 它模仿Excel的行为,包括更新/拉伸公式和其他更新:

public void InsertRows(int rowNumber, int rowCount)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM