Create Excel Files Using JavaScript

Create Excel Files Using JavaScript

SheetJS can be used in your website or JavaScript-based application to create and manipulate Excel workbooks. Manipulating Excel sheets can be done in other languages as well, but if you're JavaScript inclined or trying to add an export feature to your website, SheetJS is the way to go.

There are 2 versions of SheetJS. One is a free and open-source community version. The pro version has more features including styling. In this tutorial, I'll be using the community version.

To use SheetJS you first have to add the following script tag to your HTML.

<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>

Create a workbook

Start by creating a new workbook by calling the book_new() utility function which will return an empty workbook object.

let wb = XLSX.utils.book_new();

You can update the workbook properties with wb.Props

wb.Props = {
  Title: 'Excel Workbook',
  Subject: 'Tutorial',
  Author: 'Erich Buelow',
  CreatedDate: new Date(),
};

Create and add a worksheet

You can use aoa_to_sheet to make a sheet and book_append_sheet to append the sheet to the workbook.

Create the sheet's content by creating an array of arrays.

let wsName = 'newSheet';

let wsData = [
  ['A1', 'A2'],
  ['B1', 'B2'],
];

Create the sheet using aoa_to_sheet.

let ws = XLSX.utils.aoa_to_sheet(wsData);

Add the worksheet to the workbook.

XLSX.utils.book_append_sheet(wb, ws, wsName);

Exporting the workbook

XLSX.writeFile(workbook, 'out.xlsx');

All together

let wb = XLSX.utils.book_new();

wb.Props = {
  Title: 'Excel Workbook',
  Subject: 'Tutorial',
  Author: 'Erich Buelow',
  CreatedDate: new Date(),
};

let wsName = 'newSheet';

let wsData = [
  ['A1', 'B1'],
  ['A2', 'B2'],
];

let ws = XLSX.utils.aoa_to_sheet(wsData);

XLSX.utils.book_append_sheet(wb, ws, wsName);

XLSX.writeFile(wb, 'out.xlsx');

Click here to view the code on JSFiddle (Uncomment the last line to see the result)