一个非常简单的解决方案是以逗号分隔的形式指定不同的区域:
sheet.get_Range( "A1:B1,E1:G1");
对于编程范围组合,还有 ExcelApplication 对象的 Union 和 Intersection 方法。由于许多可选参数,这些在 C# 中使用起来有点笨拙。看这里
http://codeidol.com/csharp/c-sharp-in-office/Working-with-Excel-Objects/Working-with-the-Range-Object/
例如。
编辑:一些额外的提示:
在您的情况下,您首先应该在“ColumnsToKeep”中转换“ColumnsToSkip”,因为这是任何类型的单元格联合都需要的。这是一个 Linq 解决方案:
int[] ColumnsToKeep = Enumerable.Range(StartColumn, EndColumn -StartColumn + 1)
.Except(ColumnsToSkip)
.ToArray();
然后,您可以按照此示例的思路创建一些东西:
Excel.Range totalRange = null;
foreach(int col in ColumnsToKeep)
{
totalRange = Union(excelApp,totalRange,(Excel.Range)sh.Cells[row, col]);
}
其中定义了“Union”,例如,如下所示:
static Excel.Range Union(Excel.Application app, Excel.Range r1, Excel.Range r2)
{
if (r1 == null && r2 == null)
return null;
if (r1 == null)
return r2;
if (r2 == null)
return r1;
return app.Union(r1, r2,
null, null, null, null, null, null,
null, null, null, null, null, null,
null, null, null, null, null, null,
null, null, null, null, null, null,
null, null, null, null);
}