如何在 Angular 浏览器中导出和下载 XLSX(最小示例)

此示例使用 xlsx 库和 file-saver 库在客户端创建(空)XLSX 文件并下载。

首先,安装库:

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

使用以下方式导入

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

这是创建 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');

Check out similar posts by category: Typescript