具有多个区域的Excel Get_Range

问题描述

| 我正在尝试从Excel获得一个范围,该范围指定了多个区域,实际上我已经... int StartColumn int EndColumn int [] ColumnsToSkip 当您将这些结合使用时,可能会产生具有不连续区域的范围。不幸的是,我不能完全弄清楚获得此请求的电话... MSDN不是很有用... 工作表;
sheet.get_Range( what goes in here??? );
有人提供帮助吗?干杯。     

解决方法

        一个非常简单的解决方案是以逗号分隔的形式指定不同的区域:
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]);
   }
例如,其中定义了“联合”,例如:
    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);
    }
    ,        使用非连续范围的另一种方法是使用命名范围在Excel中将它们组合在一起,例如:
=CHOOSE({1;2;3},RANGE1,RANGE2,RANGE3)
这将产生一个数组,该数组由相互重叠的范围“ stacked”组成。将此公式分配给一个命名范围,您就可以像其他任何“ 8”对象一样以编程方式使用它。