Search code examples
javascriptnode.jsworksheet-functionworksheetsheetjs

how to delete a worksheet from a workbook in Node.js? // TypeError: Cannot read property 'delete' of undefined


I need to delete a worksheet from a workbook of an Excel in Node.js. I use the SheetJs (I would preferable need an answer using this one, but I highly appreciate all of the other possibilities, I can change). Having searching for days, but could not find the solution.

So I have this (if you need code for test):

const xlsx = require('xlsx');
workBook = xlsx.readFile("todo-list.xlsx", {cellDates:true});
const headerData = ["Id", "Name", "Description", "Due Date", "Priority", "Status", "Notes"];
const workSheet = xlsx.utils.aoa_to_sheet([headerData]);
xlsx.utils.book_append_sheet(workBook, workSheet,"TO-DEL");

and I tried this but it does not work:

workSheet.delete();

or this...

workBook.Sheets["TO-DEL"].delete();

this is how it ends:

xlsx.writeFile(workBook, 'todo-list.xlsx');

The error is: TypeError: Cannot read property 'delete' of undefined

Do you have any idea or experience with this so you can help me please? Highly appreciate any help!


Solution

  • this works perfect:

    const Excel = require('exceljs');
    
    const workbook = new Excel.Workbook();
    workbook.xlsx.readFile("todo-list.xlsx").then(function() {
            const worksheet = workbook.getWorksheet("Sheet1");
            console.log(worksheet);
            workbook.removeWorksheet(worksheet.id);
            return workbook.xlsx.writeFile( "todo-list.xlsx");
    });