Search code examples
c#.netexcelopenxmlclosedxml

ClosedXML relative range Exception in sample code


I had a problem with selecting relative range to another range inside worksheet in ClosedXML. So to be sure how it works I tried example code.

var ws = wb.Worksheets.Add("Sample Sheet");

// From worksheet
var rngTable = ws.Range("B2:F6");

// From another range
var rngDates = rngTable.Range("D3:D5");  // works, range inside B2:F6
var rngNumbers = rngTable.Range("E3:E5");// works, range inside B2:F6

var rngHeaders = rngTable.Range("A2:E2"); // this line throws an exception

It seems that the ranges are not relative after all? If the selected range is inside "B2:F6" range it works.

I used the code from here: ClosedXML Wiki

Exception


Solution

  • This behaviour was changed and the wiki is now out of date. Thanks for the catch. When specifying ranges in A1:D4 format, they are now indeed relative to the worksheet. Use this overload for sub ranges relative to the parent range:

    IXLRange.Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn);