Post

Creating XLSX Documents in Javascript (Basic)

In this post we’ll look at how to create basic XLSX documents in JavaScript using the xlsx package. This works in both NodeJS and React.

  1. What we are Making
  2. Installing Requirements
  3. The Code

What we are Making

  • We’ll look at how to add styling and formulas here in the advanced version of this guide.


Installing Requirements

Install the xlsx package using the following command:

1
npm i xlsx


The Code

To generate the above example, our output data needs to be an Array of String Arrays. Each Array represents a single row in the document:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// import XLSX from 'xlsx'; // Use this for React
const XLSX = require('xlsx');

// Create a new blank XLSX Document
let workbook = XLSX.utils.book_new();

// The data that will be added to the sheet
let dataForSheet = [
	['Column 1', 'Column 2','Column 3','Column 4','Column 5','Column 6'],
	['Data 1', 'Data 2','Data 3','Data 4','Data 5','Data 6'],
	['Data 7', 'Data 8','Data 9','Data 10'],
	['Data 11', 'Data 12','','','Data 13','Data 14','Data 15'],
];

// Convert the Array data to a sheet
let sheetData = XLSX.utils.aoa_to_sheet(dataForSheet);

// Add the sheet to the workbook
XLSX.utils.book_append_sheet(workbook, sheetData, 'Sheet 1');

// Save the XLSX File.
XLSX.writeFile(workbook, 'FILE_NAME.xlsx');
  • NOTE: Multiple sheets can be added to a single workbook (document).
This post is licensed under CC BY 4.0 by the author.