lender提了个需求,要求实现导出excel并且要分sheet页,博主非常依赖框架,以为框架的代码示例里会有,结果找了一圈都没看见,非常蛋疼只能自己改写代码了
在框架根目录找到 src/vendor/Export2Excel.js 文件,搜索export_json_to_excel 函数,将代码更改为如下
export function export_json_to_excel({
multiHeader = [],
header,
data,
filename,
merges = [],
autoWidth = true,
bookType = 'xlsx',
sheet = [] // 增加sheet参数
} = {}) {
/* original data */
filename = filename || 'excel-list'
var wb = new Workbook()
// 判断是否传入sheet参数
if (sheet.length === 0) {
sheet = ["sheet1"] // 处理默认sheet名
var data1 = [...data]
data1.unshift(header)
for (let i = multiHeader.length - 1; i > -1; i--) {
data1.unshift(multiHeader[i])
}
data = [[...data1]]
} else {
var datas = []
data.forEach((row, index) => {
row.unshift(header[index])
if (multiHeader.length) {
for (let i = multiHeader[index].length - 1; i > -1; i--) {
row.unshift(multiHeader[index][i])
}
}
datas.push(row)
})
data = [...datas]
}
sheet.forEach((ws_name, index) => {
var ws = sheet_from_array_of_arrays(data[index])
if (merges.length > 0) {
if (!ws['!merges']) ws['!merges'] = [];
merges.forEach(item => {
ws['!merges'].push(XLSX.utils.decode_range(item))
})
}
if (autoWidth) {
/*设置worksheet每列的最大宽度*/
const colWidth = data[index].map(row => row.map(val => {
/*先判断是否为null/undefined*/
if (val == null) {
return {
'wch': 10
};
}
/*再判断是否为中文*/
else if (val.toString().charCodeAt(0) > 255) {
return {
'wch': val.toString().length * 2
};
} else {
return {
'wch': val.toString().length
};
}
}))
/*以第一行为初始值*/
let result = colWidth[0];
for (let i = 1; i < colWidth.length; i++) {
for (let j = 0; j < colWidth[i].length; j++) {
if (result[j]['wch'] < colWidth[i][j]['wch']) {
result[j]['wch'] = colWidth[i][j]['wch'];
}
}
}
ws['!cols'] = result;
}
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
})
var wbout = XLSX.write(wb, {
bookType: bookType,
bookSST: false,
type: 'binary'
});
saveAs(new Blob([s2ab(wbout)], {
type: "application/octet-stream"
}), `${filename}.${bookType}`);
}
这里拿学校学生表做为演示示例
<template>
<el-link type="primary" :underline="false" icon="el-icon-download" @click="exportTable">导出表</el-link>
</template>
<script>
export default {
methods: {
exportTable() {
import('@/vendor/Export2Excel').then(excel => {
// 设置header
var header1 = ['姓名', '性别', '年龄', '班级']
var header2 = ['班级', '学生数']
// 设置data
var data1 = [['小明', '男', '12', '1'], ['小红', '女', '12', '1'], ['小刚', '男', '12', '2']]
var data2 = [['1班', '2人'], ['2班', '1人']]
excel.export_json_to_excel({
header: [header1, header2],
data: [data1, data2],
filename: '校园5年级学生表',
autoWidth: true,
bookType: 'xlsx',
sheet: ['学生5年级表', '班级5年级表'] // 设置sheet页名称
})
})
}
}
}
</script>