Shamees Ibn Yousaf
Shamees Ibn Yousaf

Reputation: 113

Unable to write data (addRow) into Excel file in Nodejs

I'm trying to write data into an Excel file using ExcelJS library. I was successfully able to create worksheet and add column data.

However, while trying to implement addRow() or addRows() method, the data is not added into the Excel worksheet.

Here is the code I tried:

 const ExcelJS = require('exceljs');
 var workbook = new ExcelJS.Workbook();
 var worksheet = workbook.addWorksheet('Payment Data');
 worksheet.columns = reportHeaders; //reportHeaders is an array of header objects

I'm able to see the columns created successfully in the excel sheet. The trouble starts from below, where I'm trying to add data (into rows):

1st method :

  worksheet.addRows(excelData);//excelData is an array of data objects

2nd method:

  for(var rowItem in excelData){
  worksheet.addRow(excelData[rowItem]);}

However, it seems either of these methods aren't working for me. Finally, the file is saved:

  workbook.xlsx.writeFile('PaymentData.xlsx')

Is there anything I'm missing? Any help will be appreciated.

Upvotes: 5

Views: 10423

Answers (2)

Vibhor
Vibhor

Reputation: 730

So the issue with your code was, you were trying to add the data to the columns without specifying the key property in the columns array and hence it was unable to add the data.

I modified the worksheet.columns array to look something like the following:

worksheet.columns = [
    { header: "A", key: "a" },
    { header: "B", key: "b" },
];

This will solve your problem

Upvotes: 12

Shamees Ibn Yousaf
Shamees Ibn Yousaf

Reputation: 113

I managed to convert the object to an array and passed it to the addRow method. This worked for me.

I'm still not sure why I'm not able to pass an array of objects to addRow method.

Upvotes: 1

Related Questions