How to export & download XLSX in the browser in Angular (minimal example)

This example uses the xlsx library and the file-saver library to create an (empty) XLSX file and download it, all on the client side.

First, install the libraries:

npm i --save file-saver xlsx
npm i --save-dev @types/file-saver

Import them using

import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

Here’s the main part of the code that creates the XLSX:

// Create an empty workbook
const wb = XLSX.utils.book_new();

// Create an empty worksheet
// If this weren't a minimal example, your data would go here
const ws = XLSX.utils.aoa_to_sheet([[]]);

// Add the worksheet to the workbook
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

// Export the workbook to XLSX format
const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'buffer' });

// Convert the binary data to a Blob
const blob = new Blob([wbout], { type: 'application/' });

// Download of the file using file-saver
saveAs(blob, 'example.xlsx');