需求背景: 需要導(dǎo)出表格的數(shù)據(jù),由于后端不提供導(dǎo)出接口,所以由前端通過(guò)JSON數(shù)據(jù)導(dǎo)出實(shí)現(xiàn)。
使用的插件:js-export-excel
安裝: npm install js-export-excel
// 導(dǎo)入依賴
const ExportJsonExcel = require('js-export-excel');
/**
* JSON數(shù)據(jù)-文件導(dǎo)出
*@param data [ 要導(dǎo)出的 object 數(shù)據(jù)]
**/
const exportFile = (data: any, fileName?: string) => {
let sheetData = [];
// 處理數(shù)據(jù)
data.forEach((item) => {
/** 表頭為參考示例,請(qǐng)根據(jù)實(shí)際情況自定義
* sheetHeader: [ '姓名', '年齡', '性別', '職業(yè)', '愛(ài)好'],
* sheetData: [['name', 'age', 'gender', 'career', 'hobby']],
**/
sheetData.push([
item.name,
item.age,
item.gender,
item.career,
item.hobby
]);
});
// 導(dǎo)出文件配置
const option: {
fileName?: string;
datas?: any;
} = {};
option.fileName = fileName || '文件名稱'; // 自定義文件名
option.datas = [
{
// 工作表名稱
sheetName: 'sheet',
// 表頭
sheetHeader: [ '姓名', '年齡', '性別', '職業(yè)', '愛(ài)好'],
// 自定義列寬
columnWidths: [10, 5, 5, 5, 10],
sheetData: sheetData,
},
];
const toExcel = new ExportJsonExcel(option);
//保存
toExcel.saveExcel();
};
使用:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-759241.html
// 自己的table 數(shù)據(jù)
exportFile (tableData, 'test');
親測(cè)有用,只要前端能拿到的是表格全量數(shù)據(jù),就能直接導(dǎo)出表格所有數(shù)據(jù)。但如果是后端分頁(yè)查詢的表格,前端每次只能查10條或20條的話,那當(dāng)前每次也只能導(dǎo)出10條20條。不然的話需要前端存一下所有的數(shù)據(jù)才能一次導(dǎo)出所有,或者后端配合提供接口返回所有數(shù)據(jù)。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-759241.html
到了這里,關(guān)于前端JS實(shí)現(xiàn)導(dǎo)出xlsx文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!