- 最近有需要前端导出Excel,涉及到复杂表格单元格合并和样式调整,在网上看了很多插件,选用了LAY-EXCEL,虽然是基于layui封装的,但是任何框架也是适用的。
http://excel.wj2015.com/_book/
- 安装npm i lay-excel,引入import LAY_EXCEL from ‘lay-excel’;
- 使用注意点:
数据的顺序
- 我封装了一个方法,代码如下
export function excel(data,merges,fileName,colWidth,rowHeigh,field,cellstyle){
let mergeConf = LAY_EXCEL.makeMergeConfig(merges)
let colConf = LAY_EXCEL.makeColConfig(colWidth, 80)
let rowConf = LAY_EXCEL.makeRowConfig(rowHeigh, 25)
let cellstyle1 = cellstyle?cellstyle:{
s: {
alignment: {
horizontal: 'center',
vertical: 'center'
}
}
}
LAY_EXCEL.setExportCellStyle(data, field+data.length, cellstyle1);
LAY_EXCEL.exportExcel({
sheet1: data
}, fileName, 'xlsx', {
extend: {
sheet1: {
'!merges': mergeConf
, '!cols': colConf
, '!rows': rowConf
}
}
});
},
Exportexcel(){
let list = [
{title:'我是标题',date:'',month1:'',month2:'',month3:'',month4:''},
{title:'内容',date:'周期',month1:'2022-12-14',month2:'',month3:'',month4:''},
{title:'xx内容',date:'天',month1:'√',month2:'√',month3:'√',month4:'√'}
];
let fileName = '复杂表头测试'
let merges = [['A1', 'F1']];
let colWidth = { 'A': 100, 'B': 100};
let rowHeigh = {1: 40,3: 25};
let field = 'A1:F';
this.$excel(list,merges,fileName,colWidth,rowHeigh,field)