Jak exportovat & stáhnout XLSX v browseru v Angular (minimální příklad)

Tento příklad používá xlsx library a file-saver library pro vytvoření (empty) XLSX souboru a jeho stažení, vše na client side.

Nejprve nainstalujte libraries:

install_deps.sh
npm i --save file-saver xlsx
npm i --save-dev @types/file-saver

Importujte je pomocí

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

Zde je main part kódu, který vytváří XLSX:

export-xlsx.ts
// 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/vnd.ms-excel' });

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

Podívejte se na podobné články podle kategorie: Typescript