How to create an Excel File with Node.js?

Sometimes, we want to create an Excel File with Node.js.

In this article, we’ll look at how to create an Excel File with Node.js.

How to create an Excel File with Node.js?

To create an Excel File with Node.js, we can use the excel4node package.

To install it, we run

npm i excel4node

Then we use it by writing

const excel = require('excel4node');

const workbook = new excel.Workbook();
const worksheet = workbook.addWorksheet('Sheet 1');
const worksheet2 = workbook.addWorksheet('Sheet 2');

const style = workbook.createStyle({
  font: {
    color: '#FF0800',
    size: 12
  },
  numberFormat: '$#,##0.00; ($#,##0.00); -'
});

worksheet.cell(1, 1).number(100).style(style);
worksheet.cell(1, 2).number(200).style(style);
worksheet.cell(1, 3).formula('A1 + B1').style(style);
worksheet.cell(2, 1).string('string').style(style);
worksheet.cell(3, 1).bool(true).style(style).style({
  font: {
    size: 14
  }
});
workbook.write('Excel.xlsx');

to create a new workbook with

const workbook = new excel.Workbook();

Then we create 2 worksheets with

const worksheet = workbook.addWorksheet('Sheet 1');
const worksheet2 = workbook.addWorksheet('Sheet 2');

Then we set the font styles of the cells with

const style = workbook.createStyle({
  font: {
    color: '#FF0800',
    size: 12
  },
  numberFormat: '$#,##0.00; ($#,##0.00); -'
});

Next, we add some content to the cells with

worksheet.cell(1, 1).number(100).style(style);
worksheet.cell(1, 2).number(200).style(style);
worksheet.cell(1, 3).formula('A1 + B1').style(style);
worksheet.cell(2, 1).string('string').style(style);
worksheet.cell(3, 1).bool(true).style(style).style({
  font: {
    size: 14
  }
});

Cell A1 is 1, 1.

And then we save the spreadsheet with

workbook.write('Excel.xlsx');

Conclusion

To create an Excel File with Node.js, we can use the excel4node package.