现有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/ 为扩展中所有文件的存放路径导出数据返回样例:
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;
// 模拟从后端接口读取需要导出的数据
$.ajax({
url: 'list.json'
,dataType: 'json'
,success(res) {
var data = res.data;
// 重点!!!如果后端给的数据顺序和映射关系不对,请执行梳理函数后导出
data = excel.filterExportData(data, [
'id'
,'username'
,'experience'
,'sex'
,'score'
,'city'
,'classify'
,'wealth'
,'sign'
]);
// 重点2!!!一般都需要加一个表头,表头的键名顺序需要与最终导出的数据一致
data.unshift({ id: "ID", username: "用户名", experience: '积分', sex: '性别', score: '评分', city: '城市', classify: '职业', wealth: '财富', sign: '签名' });
var timestart = Date.now();
excel.exportExcel(data, '导出接口数据', 'xlsx');
var timeend = Date.now();
var spent = (timeend - timestart) / 1000;
layer.alert('单纯导出耗时 '+spent+' s');
}
,error() {
layer.alert('获取数据失败,请检查是否部署在本地服务器环境下');
}
});
});
{
"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
}
]
}