5

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.

3
  • can you please create an online working demo for the project on the site like repl.it/languages/nodejs that would be much helpful. Commented Jul 11, 2020 at 12:06
  • tried something similar over repl.it/@ShameesIbn/OblongWeeklyDribbleware#index.js Commented Jul 11, 2020 at 12:59
  • Shamees you can mark the answer as the accepted answer if that worked for you. Commented Jul 13, 2020 at 10:51

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

1 Comment

Marking this answer as correct (partly); In addition to adding key property; while assigning values to excelData array I was assigning it wrong. The assignment of value should be made to the key property instead of column header. What I was doing: excelData[row].headerName = value; What I have corrected: excelData[row].key = value; (key is the value of key property corresponding to the headerName)
1

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.

1 Comment

Because you didn't define keys for your headers so it didn't know what column each object field would map to. See Vibhor's answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.