Search code examples
c#.netepplus

Using dynamic ranges with EPPlus


I need this kind of code :

// sheet.Cells is an ExcelRange
sheet.Cells["A1:E1"].Merge = true;

to be dynamic, with a base reference point :

private void CreateSection(ExcelRange basePosition)
{
    // sheet.Cells is an ExcelRange
    // E.g. if basePosition.Address is "A1", then dynamic value would be "A1:E1"
    // E.g. if basePosition.Address is "C4", then dynamic value would be "C4:G4"
    sheet.Cells["{basePosition.Address}:{basePosition.Address+4cols}"].Merge = true;
}

How can I construct such an index for using with sheet.Cells, from the basePosition?


Solution

  • I'd choose to use the .Offset() function for this. It's nice and neat and saves calculating which row/col indexes you need for the new range.

    So something like this would give a range 5 rows down and 1 column wide from your original basePosition:

    private static void CreateSection(ExcelRange basePosition)
    {
        var rangeToMerge = basePosition.Offset(0, 0, 5, 1);
        rangeToMerge.Merge = true;
    }