需求:
要求导出如上图所示的表格文件。
实现代码:
export default {
name: "exportExcelTemplate",
data() {
return {
tableData: [
[{
phase: "相位1",
desc: "南北直行,北口右转, 南北人行",
green: 10,
yellow: 10,
red: 10
},]
]
};
},
created() {
this.initTableData();
},
methods: {
initTableData() {
let tableData = [];
let phaseIndex = [4, 4, 4, 4];
for (let i = 0; i < 4; i++) {
let temp = [];
for (let j = 0; j < phaseIndex[i]; j++) {
temp.push({
phase: "相位" + j,
desc: "南北直行,北口右转, 南北人行" + j,
green: i * j,
yellow: i * j,
red: i * j
});
}
temp.push({
type: "time",
time: "09:00:18:30"
});
tableData.push(temp);
}
this.tableData = tableData;
},
getExcelDataList() {
let result = [];
// 路口信息
result.push(["路口名称"], "市心南路-南四路");
return result;
},
formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => {
return v[j]
}))
},
// 获取相位方案的多级头部
getPhaseMultiHeader() {
let result = [];
let merges = [];
let startIndex = 4;
for (let i = 0; i < this.tableData.length; i++) {
startIndex ++;
result.push(["", "", "绿灯时间", "黄灯时间", "红灯时间"]);
for (let j = 0; j < this.tableData[i].length; j++) {
startIndex ++;
if (this.tableData[i][j].type !== "time") { // 非时段处理
result.push([
this.tableData[i][j].phase,
this.tableData[i][j].desc,
this.tableData[i][j].green,
this.tableData[i][j].yellow,
this.tableData[i][j].red]);
} else { // 时段处理
result.push(["时段", this.tableData[i][j].time, "", "", ""]);
merges.push(`B${startIndex}:E${startIndex}`);
}
}
}
return [result, merges];
},
exportExcel() {
require.ensure([], () => {
const { export_json_to_excel } = require("@/common/vendor/Export2Excel");
let multiHeader = [
["信号控制方案", "", "", "", ""], //第一行
["路口名称", "市心南路-南四路", "", "", ""], // 第二行
["运行日期", "周六,周日", "", "", ""], // 第三行
["时段", "07:00-09:00;", "", "", ""], // 第四行
...this.getPhaseMultiHeader()[0]
];
const header = []; // 最后一行的表头数据
const filterVal = [];
const list = this.tableData;
const data = this.formatJson(filterVal, list)
const merges = ["A1:E1", "B2:E2", "B3:E3", "B4:E4", ...this.getPhaseMultiHeader()[1]] // 合并单元格的数据,如何合并参考上面图片的蓝色背景部分
export_json_to_excel({
multiHeader,
header,
merges,
data,
filename: "信号控制方案"
})
});
}
}
}
参考资料:https://www.liyangzone.com/2020/02/27/%E5%89%8D%E7%AB%AF/%E4%BD%BF%E7%94%A8js-xlsx%E6%8F%92%E4%BB%B6%E5%AF%BC%E5%87%BA%E5%A4%9A%E7%BA%A7%E8%A1%A8%E5%A4%B4excel/