sheetjs icon indicating copy to clipboard operation
sheetjs copied to clipboard

Question: How to remove a worksheet from existing Excel file?

Open MWallin opened this issue 6 years ago • 2 comments

Is there a way to remove an existing worksheet from a file?

I can only find methods for adding new sheets, but no way to remove a file that is already present. Am I missing something obvious or is this outside the scope of this library?

MWallin avatar Mar 09 '20 10:03 MWallin

It's not a simple operation because a bunch of different things need to be updated, but to first order you can just:

function delete_ws(wb, wsname) {
  const sidx = wb.SheetNames.indexOf(wsname);
  if(sidx == -1) throw `cannot find ${wsname} in workbook`;
  
  // remove from workbook
  wb.SheetNames.splice(sidx,1);
  delete wb.Sheets[wsname];

  // update other structures
  if(wb.Workbook) {
    if(wb.Workbook.Views) wb.Workbook.Views.splice(sidx, 1);
    if(wb.Workbook.Names) {
      const names = wb.Workbook.Names;
      for(let j = names.length - 1; j >= 0; --j) {
        if(names[j].Sheet == sidx) names = names.splice(j,1);
        else if(names[j].Sheet > sidx) --names[j].Sheet;
      }
    }
  }
}

There's probably some other metadata that needs to be updated, but that should suffice for basic workbooks

SheetJSDev avatar Mar 10 '20 04:03 SheetJSDev

Thank you, works great!

MWallin avatar Mar 10 '20 19:03 MWallin