Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to append to a excel file in nodejs

i am currently working on a form which will take user input and add it to one row of an excel sheet, as of now i have managed to make excel sheet using 3rd party plugins(node-xls to be specific). issue arises if i wanna add another row to the excel , it deletes the old entry and adds the new instead of appending the data to the next row.

tried reading the excel and then concatenating the buffers and writing the file again, but turns out it is corrupting the file and is rendering it unusable.

How do i append data to the end of the excel sheet? i am new to nodejs and buffers

var fs = require('fs');
var NodeXls = require('node-xls');
var tool = new NodeXls();
var xls = tool.json2xls({firstName: "arjun", lastName: "u", dob:"12/3/2008"}, {order:["firstName", "lastName", "dob"]});
fs.appendFile('output.xlsx', xls, 'binary', function(err){
if(err)
  alert("File is readOnly or is being used by another application,  please close it and continue!");
});
like image 273
Syed Faizan Avatar asked Aug 20 '15 18:08

Syed Faizan


People also ask

How do I append data to a node js file?

The fs. appendFile() method is used to asynchronously append the given data to a file. A new file is created if it does not exist.

How do I add rows to Xlsx?

To insert a single row: Right-click the whole row above which you want to insert the new row, and then select Insert Rows. To insert multiple rows: Select the same number of rows above which you want to add new ones. Right-click the selection, and then select Insert Rows.

What is Sheet_add_aoa?

sheet_add_aoa(ws, aoa, opts); XLSX.utils.sheet_add_aoa takes an array of arrays of JS values and updates an existing worksheet object. It follows the same process as aoa_to_sheet and accepts an options argument: Option Name.


1 Answers

Have you tried Exceljs. It helps in Read, manipulate and write spreadsheet data and styles to XLSX and JSON.

check on the below link for details

https://www.npmjs.com/package/exceljs

Your problem of adding rows or append rows is solved here:

worksheet.addRow({id: 1, name: 'John Doe', dob: new Date(1970,1,1)});

var rowValues = [];
rowValues[1] = 4;
rowValues[5] = 'Kyle';
rowValues[9] = new Date();
worksheet.addRow(rowValues);

// Add an array of rows 
var rows = [
    [5,'Bob',new Date()], // row by array 
    {id:6, name: 'Barbara', dob: new Date()}
];
worksheet.addRows(rows);
like image 162
Mohit Gupta Avatar answered Oct 01 '22 04:10

Mohit Gupta