Reafidy's edited answer is a great start,但我想对其进行扩展,而不是发表评论。 sheet.get_Range(rangeselect) 比逐行快得多,但我还没有看到提到的一件事是 get_Range 参数有 255 个字符的限制。
要绕过该限制,请照常构造一组范围,例如“8:8,10:13,14:55”,然后使用以下代码的变体:
string rangeSelectPart;
while (rangeSelect.Length >= 255)
{
rangeSelectPart = rangeSelect.Substring(0, rangeSelect.Substring(0,255).LastIndexOf(','));
Range multiRangePart = sheet.get_Range(rangeSelectPart, Type.Missing);
//do something with the range here using multiRangePart
rangeSelect= rangeSelect.Substring(rangeSelectPart.Length + 1);
}
Range multiRange = sheet.get_Range(rangeSelect, Type.Missing);
// do the same something with the last part of the range using multiRange
// now that the remaining rows are described in less than 255 characters
这将比对单个行执行操作要快得多,但在呈现大型非连续行集时也不会失败。
请注意SutharMonil's answer is way faster IFF 在连续矩形范围内设置值。从 C# 到 excel 的瓶颈通常是通过 COM 对象的重复调用,这些对象在创建和更新时阻塞,他的回答很好地整合了调用。
不幸的是,到目前为止,在我的测试中,尝试使用它来处理不是字符串类型的非字符串属性会导致类型错误。例如:
object[,] colors;
//use C# to set appropriate colors to each location in array...
for(int i = 0; i < colors.get_Length(0); i++){
for(int j = 0; j < colors.get_Length(1); j++){
colors[i,j] = XlThemeColor.xlThemeColorAccent6;
}
}
//below causes a type error
formatRange.Interior.ThemeColor = color;
如果我让它工作,我会尽量记住更新。
最后对于重复操作设置Globals.ThisAddIn.Application.ScreenUpdating = false;,然后在完成后将其设置为true。如果没有这个,Excel 会在每组范围属性更新后停止更新屏幕,这会增加操作的大量时间。