源码:
//表格导出
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);
};
代码展示:
<button class="layui-btn layui-btn-xs layui-btn-primary exportlayui">layui导出</button>
function hstable(data,totalRow) {
var table = layui.table;
//第2个实例
var ins1=table.render({
elem: '#hstable',
height: "full-70",
// width: 7* CLIENTWIDTH / 10,
size: 'sm' ,
filter:{
bottom:false
},
id: 'exportTable',识别数据的id
// defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
// title: '提示'
// ,layEvent: 'LAYTABLE_TIPS'
// ,icon: 'layui-icon-tips'
// }],
totalRow:totalRow,
page: true,
limit:200,
limits:[15,30,50,100,200,500,1000,2000,5000,10000],
cols: [columns],
data: data? data : [],
});
//由于内部会自己调用一次,所以第一次加载的时候先进行解绑
$(".exportlayui").unbind("click");
//点击按钮触发导出事件
$(".exportlayui").click(function(){
table.exportFile('exportTable', data,'xls');
});
// layer.prompt({title: '导出文件名称'}, function (val, index) {
// table.exportFile(ins1.config.id, data,'xls',val);
// layer.closeAll();
// });
// })
}
layui导出弊端:
1,数据表格列宽不能根据字段长度自动设置
2,对于数字的字符串会默认为字符串,识别数据类型单一,文本靠左,数值靠右
excel导出数据
参考链接:layui导出表格全部数据