需求背景:纯前端导出
实现思路:
XLSX插件
的 XLSX.utils.book_new()
方法,创建excel工作蒲对象wb。XLSXS.utils.book_new()
, 创建excel表格对象wb。XLSX.utils.book_append_sheet()
,生成实际excel工作蒲,并使用XLSX.writeFile()
生成excel文件。组件代码
<!--把数据导出到excel-->
<template>
<span style="padding:0 2px">
<el-button
plain
icon="el-icon-download"
type="primary"
size="mini"
:disabled="disabled"
@click="exportToExcel"
>{{ $t('export') }}</el-button>
</span>
</template>
<script>
import XLSX from 'xlsx'
import XLSXS from 'xlsx-js-style'
export default {
name: 'ExportExcel',
props: {
tableName: {
type: String,
default: () => {
return this.$t('exportTable')
}
},
sheetName: { type: String, default: 'sheet1' },
tableData: {
type: Array,
default: () => {
return []
}
},
columns: {
type: Array,
default: () => {
return []
}
},
setColorPropList: {
// 对值进行颜色设置的列
type: Array,
default: () => {
return []
}
},
disabled: { type: Boolean, default: false }
},
data() {
return {}
},
methods: {
exportToExcel() {
const headData = []
const props = []
const colWidth = []
this.columns.forEach((v) => {
if (v.visible) {
const headObj = {
v: v.label,
t: 's',
s: {
alignment: {
vertical: 'center', // 垂直居中
horizontal: v.align || 'left' // 水平
},
fill: {
fgColor: { rgb: 'CACACF' }
}
}
}
headData.push(headObj)
props.push(v.prop)
colWidth.push({ wch: v.width / 10 || 10 })
}
})
this.exportData(this.tableData, [headData], props, colWidth)
},
/**
* @function exportData 导出excel
* @param {Array} tableData json数据
* @param {Array} headData 表头数据[["日期", "姓名", "地址"]]
* @param {Array} colWidth 列宽
*/
exportData(tableData, headData, props, colWidth) {
const body = []
tableData.forEach((item) => {
const rowData = []
props.forEach((v) => {
const value = item[v]
const find = this.columns.find((z) => z.prop === v)
const valueObj = {
v: value,
t: 's',
s: {
alignment: {
horizontal: (find && find.align) || 'left'
},
font: {
color: { rgb: '666666' }
}
}
}
if (find && this.setColorPropList.includes(find.prop)) {
// 颜色判断
if (!isNaN(parseFloat(value))) {
if (parseFloat(value) > 0) {
valueObj.s.font.color = { rgb: 'FF0000' }
}
if (parseFloat(value) < 0) {
valueObj.s.font.color = { rgb: '008000' }
}
}
}
if (find && find.render) {
// 列中是否有render方法
valueObj.v = find.render(item, value)
}
rowData.push(valueObj)
})
body.push(rowData)
})
body.unshift(...headData)
const sheet = XLSX.utils.aoa_to_sheet(body)
sheet['!cols'] = colWidth
const wb = XLSXS.utils.book_new()
XLSXS.utils.book_append_sheet(wb, sheet, this.sheetName) // 工作簿名称
XLSXS.writeFile(wb, this.tableName + '.xlsx') // 保存的文件名
}
}
}
</script>
使用示例
<ExportExcel
tableName="数量表"
sheetName="数量表"
:columns="overviewColumns"
:table-data="exportExcelTableData"
:set-color-prop-list="['code','name']"
:disabled="false"
/>
overviewColumns: [{prop: 'code', label: '代码'}, {prop: 'name', label: '名称'}, {prop: 'amount', label: '数量'}],
exportExcelTableData: [{code: 'XXX', name: 'name1', amount: 10}]