You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
3.8 KiB
JavaScript

layui.config({
base: './../../static/layui/layui_exts/'
}).use(['table', 'excel'], function () {
var table = layui.table //表格
,
$ = layui.$,
excel = layui.excel;
var LIST_TABLE_ID = "listTable"; // table ElementId
$(".export-button").click(function (e) {
exportFile('listTable');
});
//执行一个 table 实例
table.render({
elem: '#listTable',
height: 420,
data: [{ id: 1, username: '小毛', city: '长沙', birth: '1990-06-16', createTime: '2020-01-01', remark: '备注' }],
// url: './data.json', //数据接口
title: '用户表',
page: true, //开启分页
toolbar: '#toolbarDemo', //操作1:启用自定义模板表格头部工具栏
defaultToolbar: [], //操作2:隐藏头部工具栏右侧的图标
cols: [
[ //表头
{
type: 'checkbox',
fixed: 'left'
}, {
field: 'id',
title: 'ID',
width: 200,
sort: true
}, {
field: 'username',
title: '用户名',
width: 100
}, {
field: 'city',
title: '城市',
width: 100
}, {
field: 'birth',
title: '生日',
width: 120,
sort: true,
totalRow: true
}, {
field: 'createTime',
title: '创建日期',
width: 180
}, {
field: 'remark',
title: '备注',
width: 300
}
]
]
});
//监听头工具栏事件
table.on('toolbar(test)', function (obj) {
var checkStatus = table.checkStatus(obj.config.id),
data = checkStatus.data; //获取选中的数据
switch (obj.event) {
case 'table_export':
exportFile('demo')
break;
};
});
/**
* by yutons
* Array.from() 非常方便的将一个类数组的集合 == 数组直接使用数组身上的方法例如常用的mapforeach
* 但是问题来了IE不识别Array.from这个方法所以写了它兼容IE的写法
*/
if (!Array.from) {
Array.from = function (el) {
return Array.apply(this, el);
}
}
//表格导出
function exportFile(id) {
//根据传入tableID获取表头
var headers = $("div[lay-id=" + id + "] .layui-table-box table").get(0);
var htrs = Array.from(headers.querySelectorAll('tr'));
var titles = {};
for (var j = 0; j < htrs.length; j++) {
var hths = Array.from(htrs[j].querySelectorAll("th"));
for (var i = 0; i < hths.length; i++) {
var clazz = hths[i].getAttributeNode('class').value;
if (clazz != ' layui-table-col-special' && clazz != 'layui-hide') {
//排除居左、具有、隐藏字段
//修改:默认字段data-field+i,兼容部分数据表格中不存在data-field值的问题
titles['data-field' + i] = hths[i].innerText;
}
}
}
//根据传入tableID获取table内容
var bodys = $("div[lay-id=" + id + "] .layui-table-box table").get(1);
var btrs = Array.from(bodys.querySelectorAll("tr"))
var bodysArr = new Array();
for (var j = 0; j < btrs.length; j++) {
var contents = {};
var btds = Array.from(btrs[j].querySelectorAll("td"));
for (var i = 0; i < btds.length; i++) {
for (var key in titles) {
//修改:默认字段data-field+i,兼容部分数据表格中不存在data-field值的问题
var field = 'data-field' + i;
if (field === key) {
//根据表头字段获取table内容字段
contents[field] = btds[i].innerText;
}
}
}
bodysArr.push(contents)
}
//将标题行置顶添加到数组
bodysArr.unshift(titles);
//导出excel
excel.exportExcel({
sheet1: bodysArr
}, '表' + new Date().toLocaleString() + '.xlsx', 'xlsx');
}
});