pmiranda
pmiranda

Reputation: 8420

JavaScript, json to excel (exceljs)

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?

Upvotes: 2

Views: 5947

Answers (2)

3ximus
3ximus

Reputation: 391

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);

Upvotes: 2

davidhu
davidhu

Reputation: 10434

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

Upvotes: 1

Related Questions