首先引用xlsx
首先是导出方法
// 导出
exportExcel() {
// 格式化数据为二维数组
this.exportData = this.formatTableData()
// 设置表格数据
const ws = XLSX.utils.aoa_to_sheet(this.exportData)
// 新建一个工作簿
const wb = XLSX.utils.book_new()
// 设置表格样式,!cols为列宽
const options = { '!cols': [] }
for (const key in this.tableLabel) {
options['!cols'].push({ wpx: this.tableLabel[key] })
}
ws['!cols'] = options['!cols']
// 将工作表添加到工作簿
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
// 输出工作表,由文件名决定的输出格式
const fileNamePrefix = this.unitTestCoverObj.applicationName
const time = getFullTime(null, true).replace(/-/g, '')
const fileName = `${fileNamePrefix}${time}.xlsx`
XLSX.writeFile(wb, fileName)
this.$message({
type: 'success',
message: '导出成功'
})
}
格式化数据为二维数组
// 数据格式为二维数组
formatTableData() {
const data = []
let tableRef = null
tableRef = this.$refs.unitTestCoverTable
data.push(...this.unitTestCoverData)
if (!tableRef) {
console.error('找不到表格组件ref')
return []
}
const array = []
array[0] = []
this.tableLabel = {}
for (const obj of tableRef.columns) {
if (obj.type === 'index') {
array[0].push('序号')
this.tableLabel['index'] = obj.width
} else {
array[0].push(obj.label)
this.tableLabel[obj.property] = obj.width || obj.minWidth || obj.realWidth || 100
}
}
data.forEach((item, index) => {
const subArray = []
for (const head of Object.keys(this.tableLabel)) {
if (head === 'index') {
subArray.push(index + 1)
continue
}
if (item[head] !== undefined) {
if (head === 'coverage' || head === 'branchCoverage') {
subArray.push(`${item[head]}%`)
} else {
subArray.push(`${item[head]}`)
}
} else {
subArray.push('')
}
}
array.push(subArray)
})
console.log(array)
return array
}
console到控制台看一眼是这样的:
第一组对象为xsml表格第一排