I have an array of objects as shown below:
[
{ "FirstName": "John",
"LastName": "Parker",
"Age": "23",
"Cat": "23g",
"SOP": "Active"
},
{ "FirstName": "Rose",
"LastName": "Jackson",
"Age": "44",
"Cat": "44g",
"SOP": "InActive"
}
]
I am using excel4node to create and write the object's data to the excel
async generateExclReport(req, res) {
try {
var wb = new xl.Workbook();
// Add Worksheets to the workbook
var ws = wb.addWorksheet('Report');
ws.cell(1, 1).string('FirstName');
ws.cell(1, 2).string('LastName');
ws.cell(1, 3).string('Age');
ws.cell(1, 4).string('Cat');
ws.cell(1, 5).string('SOP');
var fileName = "Report" + Date.now().toString() + '.xlsx';
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
wb.write(fileName, res);
} catch (err) {
this.handleError(res, err);
}
}
I am able to print the headers in the excel and download but how can I print the object's data in the excel?
Any help is highly appreciated.
You can loop through your data and make sure that you skip the header row that you created.
Excel rows start at row
1and your array is index0so you need to make sure that you always start at either1when writing to Excel or in your case start at row2since you created a header row (that's why you'll seews.cell(i + 2, 1).string(data[i].FirstName);).Here is a sample express app:
Dependencies:
Code: