現(xiàn)有Excel操作前端庫中,XLSX.JS功能強大但是操作頗為不便,于是封裝了此插件,依賴jQuery,支持Layui插件形式加載,導出僅需一句話。 導出excel功能基于 XLSX.js,下載功能基于 FileSaver,讀取文件基于 H5的 FileReader。
{
"code":0,
"msg":"",
"count":3,
"data":[
{
"id":10000,
"username":"user-0",
"sex":"女",
"city":"城市-0",
"sign":"簽名-0",
"experience":255,
"logins":24,
"wealth":82830700,
"classify":"作家",
"score":57,
"start": '2018-12-29',
"end": "2018-12-30"
}
]
}
// 注:lay_exts/ 為擴展中所有文件的存放路徑導出數(shù)據(jù)返回樣例:
layui.config({
base: 'lay_exts/',
}).extend({
excel: 'excel',
});
layui.use(['jquery', 'excel', 'layer'], function() {
var $ = layui.jquery;
var layer = layui.layer;
var excel = layui.excel;
// 模擬從后端接口讀取需要導出的數(shù)據(jù)
$.ajax({
url: 'list.json'
,dataType: 'json'
,success(res) {
var data = res.data;
// 重點!?。∪绻蠖私o的數(shù)據(jù)順序和映射關系不對,請執(zhí)行梳理函數(shù)后導出
data = excel.filterExportData(data, [
'id'
,'username'
,'experience'
,'sex'
,'score'
,'city'
,'classify'
,'wealth'
,'sign'
]);
// 重點2!?。∫话愣夹枰右粋€表頭,表頭的鍵名順序需要與最終導出的數(shù)據(jù)一致
data.unshift({ id: "ID", username: "用戶名", experience: '積分', sex: '性別', score: '評分', city: '城市', classify: '職業(yè)', wealth: '財富', sign: '簽名' });
var timestart = Date.now();
excel.exportExcel(data, '導出接口數(shù)據(jù)', 'xlsx');
var timeend = Date.now();
var spent = (timeend - timestart) / 1000;
layer.alert('單純導出耗時 '+spent+' s');
}
,error() {
layer.alert('獲取數(shù)據(jù)失敗,請檢查是否部署在本地服務器環(huán)境下');
}
});
});
{
"code":0,
"msg":"",
"count":3,
"data":[
{
"id":10000,
"username":"user-0",
"sex":"女",
"city":"城市-0",
"sign":"簽名-0",
"experience":255,
"logins":24,
"wealth":82830700,
"classify":"作家",
"score":57
},
{
"id":10001,
"username":"user-1",
"sex":"男",
"city":"城市-1",
"sign":"簽名-1",
"experience":884,
"logins":58,
"wealth":64928690,
"classify":"詞人",
"score":27
},
{
"id":10002,
"username":"user-2",
"sex":"女",
"city":"城市-2",
"sign":"簽名-2",
"experience":650,
"logins":77,
"wealth":6298078,
"classify":"醬油",
"score":31
}
]
}