业务中经常会处理各种数据,本文介绍了前端通过 xlsx 库将数据转换为 excel 文件用于上传的实现。
import * as XLSX from "xlsx"; // 此代码使用版本 0.18.5
interface ObjectAny {
[key: string]: any;
}
const exportExcelNoDownload = (headers: string[][], data: ObjectAny[]): File => {
const headerWs = XLSX.utils.aoa_to_sheet(headers);
const ws = XLSX.utils.sheet_add_json(headerWs, data, {skipHeader: true, origin: 'A2'});
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'sheet1');
const fileData = XLSX.write(wb, {type: 'array', compression: true}); // compression 能有效减少文件体积,便于上传
const newFile = new File([fileData], 'text.xlsx');
return newFile;
}
// 本地测试一下生成的文件是否正常
const test = () => {
const headers = [['国家', '城市']];
const data = [
{'国家': 'china', '城市': 'shenzhen'},
{'国家': 'china', '城市': 'guangzhou'},
{'国家': 'USA', '城市': 'newyork'},
];
const file = exportExcelNoDownload(headers, data);
const tmpLink = document.createElement("a");
const objectUrl = URL.createObjectURL(file);
tmpLink.href = objectUrl;
tmpLink.download = file.name;
document.body.appendChild(tmpLink);
tmpLink.click();
document.body.removeChild(tmpLink);
URL.revokeObjectURL(objectUrl);
}