Reputation: 572
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:
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 ?
Upvotes: 2
Views: 9864
Reputation: 1
//I tried this is not working.Please have a look.
const XLSX = require('xlsx')
var filename = './customer_data.xlsx'
var workbook = XLSX.readFile(filename)
var worksheet = workbook.Sheets[workbook.SheetNames[0]]
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"])
console.log(variable);
for (var R = row_index; R < variable.e.r; ++R) {
for (var C = variable.s.c; C <= variable.e.c; ++C) {
console.log(C);
ws[ec(R, C)] = ws[ec(R + 1, C)];
}
}
variable.e.r--
ws['!ref'] = XLSX.utils.encode_range(variable.s, variable.e);
}
var result = delete_row(worksheet, 2);
console.log(result);
Upvotes: 0
Reputation: 572
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)
Upvotes: 3