2

I have to maintain a code that do a weird and slow loops.

Currently it's looping in a while each object from a JSON like this one (example JSON):

[
  {
    ID: 1,
    NAME: 'A'
  }, {
    ID: 3,
    NAME: 'D'
  },{
    ID: 5,
    NAME: 'etc'
  }
]

And it's creating an excel file with exceljs library but as I said, with some loops that I consider really unnecesary.

The idea is to create an excel file like this:

ID | NAME
---------
1  |  A
3  |  D
5  |  etc

So I wonder if there's a direct way with exceljs or another Excel library for NodeJS to create a simple excel file from a JSON, where each key of the JSON be a header value, and each value of thos key: value pairs be the value of the cell in the excel?

2 Answers 2

3

The previous answer by @davidhu doesn't work. You'll have to setup the columns before adding the rows as a JSON:

const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('My Sheet');

worksheet.columns = [
  { letter: 'A', header: 'ID', key: 'ID' },
  { letter: 'B', header: 'NAME', key: 'NAME' },
];

const rows = [
  { ID: 1, NAME: 'A' },
  { ID: 3, NAME: 'D' },
  { ID: 5, NAME: 'etc' },
];

const newRows = worksheet.addRows(rows);
Sign up to request clarification or add additional context in comments.

Comments

0

Looks like you can just add the json array

const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('My Sheet');

const rows = [
  {
    ID: 1,
    NAME: 'A'
  }, {
    ID: 3,
    NAME: 'D'
  },{
    ID: 5,
    NAME: 'etc'
  }
]

const newRows = worksheet.addRows(rows);

https://github.com/exceljs/exceljs#add-rows

1 Comment

The mapping is done based on column key mapping

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.