简体   繁体   English

从Excel.Interop表中删除并插入多行

[英]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? 假设我想删除一定范围的行,例如210-560、10-11等。是否可以像下面的示例一样在一行内完成操作,还是需要创建一个具有范围的循环数字以删除范围?

C# 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: 使用VBA时,可以使用这样的简单方法:

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: 如果要执行与C#中的VBA代码相同的操作,则可以简单地编写:

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. 行字符串的大小限制为255个字符。 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 .) (只是为了简便起见,我没有在这个例子中显示出任何大的字符串。 application是当前的实例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. 唯一需要注意的是:您必须使用在“控制面板”的“ Windows区域设置”中指定的列表分隔符。 This is especially important if you deliver your application globally or to unknown users (like an ISV). 如果您在全球范围内或向未知用户(例如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: 您可以使用以下方法从Windows区域设置中获取当前列表分隔符:

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

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

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