Search code examples
javascriptnode.jsexcelxlsxsheetjs

How to delete an existing row of a worksheet in Excel by using XLSX in node js?


How to delete an existing row of a worksheet of a workbook in Excel by using the XLSX from SheetJS in Node.js?

The code so far:

const xlsx = require('xlsx');

// read the file
workBook = xlsx.readFile("todo-list.xlsx", {cellDates:true});

// read the worksheet
const shoppingList = workBook.Sheets["Do-Shopping"];

// delete a specific row
........ [here I dont know even how to start]

// write the data to the Excel file
xlsx.writeFile(workBook, 'todo-list.xlsx');

Desired results:

BEFORE: before AFTER: after

But the deleted row could be anyone, like the first one or the third one, not necessary the last one.

I tried searching on the official docs and stack, but I have not found an answer yet. :( and I am new to Node js

Could you please help me ?


Solution

  • Answer found on the Github's site, works very well on any row:

    // delete a specific row
    function ec(r, c){
        return xlsx.utils.encode_cell({r:r,c:c});
    }
    function delete_row(ws, row_index){
        var variable = xlsx.utils.decode_range(ws["!ref"])
        for(var R = row_index; R < variable.e.r; ++R){
            for(var C = variable.s.c; C <= variable.e.c; ++C){
                ws[ec(R,C)] = ws[ec(R+1,C)];
            }
        }
        variable.e.r--
        ws['!ref'] = xlsx.utils.encode_range(variable.s, variable.e);
    }
    delete_row(shoppingList, 1)