Excel Get_Range with multiple areas

后端 未结 3 1010

I\'m trying to get a range from Excel, which has multiple areas specified, essentially I\'ve got...

int StartColumn
int EndColumn
int[] ColumnsToSkip

3条回答
  •  Happy的楠姐
    2020-12-19 03:30

    A very simple solution is to specify different areas in comma-separated form:

    sheet.get_Range( "A1:B1,E1:G1");
    

    For programmatic range combinations, there are also the Union and Intersection methods of the ExcelApplication object. Those are a little bit clumsy to use in C# because of many optional parameters. See here

    http://codeidol.com/csharp/c-sharp-in-office/Working-with-Excel-Objects/Working-with-the-Range-Object/

    for examples.

    EDIT: some additional hints:

    In your case, you first should transform the "ColumnsToSkip" in "ColumnsToKeep", since that is what you will need for any kind of cell union. Here is a Linq solution:

    int[] ColumnsToKeep = Enumerable.Range(StartColumn, EndColumn -StartColumn + 1)
                          .Except(ColumnsToSkip)
                          .ToArray();
    

    Then, you can create something along the lines of this example:

       Excel.Range totalRange = null;
       foreach(int col in ColumnsToKeep)
       {
            totalRange = Union(excelApp,totalRange,(Excel.Range)sh.Cells[row, col]);
       }
    

    where "Union" is defined, for example, like this:

        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);
        }
    

提交回复
热议问题