常见问题
- table.exportFile is not a function
let table = layui.table.render
table.exportFile(); // Uncaught TypeError: table.exportFile is not a function
// 这个Table, 只是layui table 生成的一个对象只有这些函数(如下图)
// 解决办法: 使用layui.table;
console.log(layui.table);
layui.table.exportFile();
- table.exportFile = function(id, data, type) 的三个参数
id:是设置的表格ID
data: 是传入的相应数据
type:输出的文件类型(csv | xls)
参数详解
-
id 设置方式:
- 通过初始化设置
- 由layui自己设置
options.id = options.id || options.elem.attr('id') || that.index; /* 第一个是自己设置的ID, 第二个是通过获取ID标签的ID("#xxxxxx" => "xxxxxx"), 第三个则是序号 */
- 通过初始化设置
-
data 设置方式
- 如果为undefined 会自动获取表格内数据
data = data || table.clearCacheKey(table.cache[id]);
- 自己的数据打印出来则是自己的数据
table.exportFile(['名字','性别','年龄'], [ ['张三','男','20'], ['李四','女','18'], ['王五','女','19'] ], 'csv'); //默认导出 csv,也可以为:xls
-
type 设置方式
字符串 csv | xls
输出表格
<table id="order-list">
</table>
// 有了前面的基础之后,这些就简单了
layui.table.exportFile("order-list");
exportFile 源码
//表格导出
table.exportFile = function(id, data, type){
var that = this;
data = data || table.clearCacheKey(table.cache[id]);
type = type || 'csv';
var config = thisTable.config[id] || {}
,textType = ({
csv: 'text/csv'
,xls: 'application/vnd.ms-excel'
})[type]
,alink = document.createElement("a");
if(device.ie) return hint.error('IE_NOT_SUPPORT_EXPORTS');
alink.href = 'data:'+ textType +';charset=utf-8,\ufeff'+ encodeURIComponent(function(){
var dataTitle = [], dataMain = [], dataTotal = [];
//表头和表体
layui.each(data, function(i1, item1){
var vals = [];
if(typeof id === 'object'){ //如果 id 参数直接为表头数据
layui.each(id, function(i, item){
i1 == 0 && dataTitle.push(item || '');
});
layui.each(table.clearCacheKey(item1), function(i2, item2){
vals.push('"'+ (item2 || '') +'"');
});
} else {
table.eachCols(id, function(i3, item3){
if(item3.field && item3.type == 'normal' && !item3.hide){
var content = item1[item3.field];
if(content === undefined || content === null) content = '';
i1 == 0 && dataTitle.push(item3.title || '');
vals.push('"'+ parseTempData(item3, content, item1, 'text') + '"');
}
});
}
dataMain.push(vals.join(','));
});
//表合计
layui.each(that.dataTotal, function(key, value){
dataTotal.push(value);
});
return dataTitle.join(',') + '\r\n' + dataMain.join('\r\n') + '\r\n' + dataTotal.join(',');
}());
alink.download = (config.title || 'table_'+ (config.index || '')) + '.' + type;
document.body.appendChild(alink);
alink.click();
document.body.removeChild(alink);
};
结语
此版本为 layui 2.4.6 版本