N
N
Neuro2019-07-02 13:00:37
JavaScript
Neuro, 2019-07-02 13:00:37

How to create xls file based on js array, exceljs?

Good afternoon.
I want to create an xls file with a table that will display a js object using the exeljs library.
I read a little documentation and wrote just such a function, which, based on the fakeData constant, should create a table.

"use strict";

var Excel = require('exceljs');

exports.wrap = () => {
  const workbook = new Excel.Workbook();
  const worksheet = workbook.addWorksheet('Sensor Data');
  const fakeData =  {
    address: "well st",
    description: "180036710",
    fromTotal: 1.365
  };
  worksheet.addRow(fakeData)

  worksheet.columns = [
    { header: 'address', key: 'address', width: 10 },
    { header: 'description', key: 'description', width: 32, style: { font: { name: 'Arial Black' } } },
    { header: 'fromTotal.', key: 'fromTotal', width: 10, style: { numFmt: 'dd/mm/yyyy' } }
  ];

  return workbook.xlsx.writeFile("test.xlsx");
};

It seems that everything was done correctly, but the function does not work and an empty file is downloaded, maybe someone has already worked with this either and will tell you where I messed up

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TaF, 2020-12-10
@Riveran

You didn't take into account saving (commit) and the line for adding a row should be omitted below the description of the columns. The working version looks like this:

"use strict";

var Excel = require('exceljs');

exports.wrap = () => {
  const workbook = new Excel.Workbook();
  const worksheet = workbook.addWorksheet('Sensor Data');
  const fakeData =  {
    address: "well st",
    description: "180036710",
    fromTotal: 1.365
  };
  worksheet.columns = [
    { header: 'address', key: 'address', width: 10 },
    { header: 'description', key: 'description', width: 32, style: { font: { name: 'Arial Black' } } },
    { header: 'fromTotal.', key: 'fromTotal', width: 10, style: { numFmt: 'dd/mm/yyyy' } }
  ];
  worksheet.addRow(fakeData).commit();
  return workbook.xlsx.writeFile("test.xlsx");
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question