Brandon Brandon - 10 months ago 87
C# Question

Deleting and inserting multiple rows from a Excel.Interop table

Is it possible to delete and insert multiple rows within a table? Lets say I wanted to delete a range of rows whether its 210-560, or 10-11. Is it possible to do it within one line as I have exampled below, or will I need to create a loop with a range of numbers in order to delete a range?




While using VBA you were able to use a simple method like this:


Answer Source

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

var ws = xlWorkBook.Worksheets["Sheet1"];

You can even specify multiple rows at once:


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). E.g. 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];