sheetjs icon indicating copy to clipboard operation
sheetjs copied to clipboard

Worksheet Dimensions: fix examples by automatically deducing range

Open Vanuan opened this issue 6 years ago • 2 comments

There's this !ref property that corresponds to Worksheet Dimensions.

Documentation states:

It specifies the row and column bounds of used cells in the worksheet When an entire column is formatted, only the first cell in that column is considered used.

Specifically the ref property:

The row and column bounds of all cells in this worksheet. Corresponds to the range that would contain all elements written under <sheetData>. Does not support whole column or whole row reference notation.

The can be various interpretation on whether "used cells" refers to formatting or to cell elements.

Anyway, ref property is unreliable. So I suggest fixing examples to determine range with the following code:

    const cells = Object.keys(sheet).map((key) => dc(key))
    const maxRow = maxBy(cells, 'r').r;
    const maxCol = maxBy(cells, 'c').c;

    range.max = {r: maxRow, c: maxCol};

Vanuan avatar Aug 15 '19 15:08 Vanuan

The wiki has a sample for updating worksheet range

The "fix" is to change the parsers to recalculate the range, not pushing the code to end users

SheetJSDev avatar Sep 11 '21 21:09 SheetJSDev

Since that the link to the wiki isn't working anymore, here is the function from the new documentation that updates the "real" range of the spreadsheet

function update_sheet_range(ws) {
  var range = {s:{r:Infinity, c:Infinity},e:{r:0,c:0}};
  Object.keys(ws).filter(function(x) { return x.charAt(0) != "!"; }).map(XLSX.utils.decode_cell).forEach(function(x) {
    range.s.c = Math.min(range.s.c, x.c); range.s.r = Math.min(range.s.r, x.r);
    range.e.c = Math.max(range.e.c, x.c); range.e.r = Math.max(range.e.r, x.r);
  });
  ws['!ref'] = XLSX.utils.encode_range(range);
}

Nairolf92 avatar Feb 01 '23 09:02 Nairolf92