简体   繁体   中英

Deleting and inserting multiple rows from a Excel.Interop table

Is it possible to delete and insert multiple rows within a table? Let's say I wanted to delete a range of rows, for example 210-560, 10-11 etc. Is it possible to do it within one line as I have in the example below, or will I need to create a loop with a range of numbers in order to delete a range?

C#

xlWorkBook.Worksheets["Sheet1"].ListObjects["Table1"].ListRows(11,12).Range.Delete();

xlWorkBook.Worksheets["Sheet1"].ListObjects["Table1"].ListRows(11,12).Range.InsertRowRange();

While using VBA one is able to use a simple method like this:

Rows("210:560").Delete
Rows("11:12").EntireRow.Insert

If you want to do the same as the VBA code in C# you can simply write:

var ws = xlWorkBook.Worksheets["Sheet1"];
ws.Range["210:560"].Delete();
ws.Range["11:12"].Insert();

You can even specify multiple rows at once:

ws.Range["210:560,722:838,917:917"].Delete();
ws.Range["11:12,15:17,19:19"].Insert();

For single rows you have to specify the row number twice like shown above.

The size limit for the string of the rows is 255 chars. If you want to handle more rows than this in one go, you have to do a union of the ranges. So for example something like this:

application.Union(ws.Range["2:5,7:8,9:9"], ws.Range["11:12,15:17,19:19"]).Delete();

(Just for the sake of brevity I didn't show any large strings in this example. application is the instance of the current Excel.Application .)

The only thing to be aware of: You have to use the list separator that is specified in the Windows Regional Settings in the Control Panel. This is especially important if you deliver your application globally or to unknown users (like an ISV). Eg for German users the default list separator would be ; and not , like for English users. But of course it can be set to nearly anything manually by the user.

You can get the current list separator from the Windows Regional Settings using this:

var sep = (string)application.International[XlApplicationInternational.xlListSeparator];

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