Install dependencies
First, you need to install the xlsx and file-saver libraries.
npm install xlsx file-saver --save
If you are interested, you can read the official instructions of the two libraries. It is no problem to use them directly below.
The SheetJS Community Edition offers battle-tested open-source solutions for extracting useful data from almost any complex spreadsheet and generating new spreadsheets that will work with legacy and modern software alike. Extract useful data from spreadsheets of almost any complexity and generate new spreadsheets that work with traditional and modern software.
SheetJS Pro offers solutions beyond data processing: Edit complex templates with ease; let out your inner Picasso with styling; make custom sheets with images/graphs/PivotTables; evaluate formula expressions and port calculations to web apps; automate common spreadsheet tasks, and much more !
SheetJS Pro offers solutions beyond data processing: easily edit complex templates; unleash your inner Picasso with styling; make custom worksheets with images/graphs/pivot tables; evaluate formula expressions and port calculations to web apps Program; automates common spreadsheet tasks, and more!
Prepare data
Prepare the table data you want to export as a two-dimensional array. for example:
const data = tabelData.map((item: any) => {
const arr: any[] = [];
item.forEach((j: any) => {
arr.push(j);
});
return arr;
});
Define export method
You need to create a function that processes the data you prepared above and returns a blob of an xlsx file.
import * as XLSX from 'xlsx';
export const exportExcel = (data: any[]) => {
// 创建一个空的工作簿
const workbook = XLSX.utils.book_new();
// 创建一个工作表
const worksheet = XLSX.utils.aoa_to_sheet(data);
// 将工作表添加到工作簿中
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
// 将工作簿转换为二进制数据流
const excelData = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
// 将二进制数据流转换为 Blob 对象
const blob = new Blob([excelData], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
return blob;
};
download file
Finally you need to download the file, you can use the function file-save
provided in the installation abovesaveAs
import { saveAs } from 'file-saver';
// 处理表格文件
const blob = exportExcel(data);
const fileName = `${item.file.name.split('.')[0]}.xlsx`;
// 下载
saveAs(blob, fileName);
ps: If used locally, the download will be normal but the browser will report a warning. This is because we use http download locally. This can be ignored. This warning will not appear online.
References
xlsx npm document file-saver npm document vue3 imports elcel table and displays it (using xlsx plug-in+vite+element-plus)/js upload table (js+xlsx)