今天接到需求,说是一个表格要做成树状数据,表格直接使用的是element ui的表格组件,但是唯一比较麻烦的就是把这个表格导出成Excel表格
做出来的样子:
有些数据就不好展示了
以下就是实现代码了
// 导出excel
async handleExportToExcel() {
// 获取接口数据
const res = await this.searchOnceData()
const data = res
// 设置表头 有多少个写多少个
const fields = {
表格里面prop的值: '表格里面label的值',
}
// 拼接标题行
const head = Object.values(fields)
.map((item) => {
return `<td>${item}</td>`
})
.join('')
const body = data
.map((item, index) => {
/* eslint-disable-next-line */
let str = `<tr style="mso-number-format:'\@';">` // 为了不让表格显示科学计数法
let chr = '<tr style="vnd.ms-excel.numberformat:@">' // 为了不让表格导出到Excel时前面是0不被删除
for (const key in fields) {
str += `<td>${item[key] != undefined ? item[key] : ''}</td>`
}
// 判断当前有没有子类,有就执行这里面代码 (处理子类有数据导出至Excel文件显示)
if (item.allDetail.length) {
item.allDetail.forEach((item) => {
for (const key in fields) {
// 声明一个变量储存子类数据的行数据拼接
chr += `<td>${item[key] != undefined ? item[key] : ''}</td>`
}
})
// 这句才是重点:拼接父级数据的行与子类数据的行,中间使用tr换行
str = str + '</tr>' + chr
}
return str + '</tr>'
})
.join('')
console.log(body, head)
// Worksheet名
const worksheet = 'Sheet1'
const uri = 'data:application/vnd.ms-excel;base64,'
// 下载的表格模板数据
const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
<x:Name>${worksheet}</x:Name>
<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
</head><body><table><tr>${head}</tr>${body}</table></body></html>`
// 下载模板
let link = document.createElement('a')
link.setAttribute('href', uri + window.btoa(unescape(encodeURIComponent(template))))
link.setAttribute('download', 'Excel表名称.xls')
link.click()
link = null
},
导出效果: