sheetjs
sheetjs copied to clipboard
Question: How to remove a worksheet from existing Excel file?
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?
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
Thank you, works great!