最近遇到一个需求就是统计列表需要前端导出,一开始觉得很难,后来发现不难,网上很多教程都是修改配置文件来操作的,这种方法是直接通过数据导出,所以会觉得麻烦,其实只需要把要导出的表格用el-table渲染出来,然后导出就行了
具体实现如下:
首先安装依赖
npm install --save xlsx file-saver
具体代码
<template>
<div>
<el-table
ref="report-table"
:data="tableData"
style="width: 100%">
<el-table-column
prop="date"
label="日期"
width="150">
</el-table-column>
<el-table-column label="配送信息">
<el-table-column
prop="name"
label="姓名"
width="120">
</el-table-column>
<el-table-column label="地址">
<el-table-column
prop="province"
label="省份"
width="120">
</el-table-column>
<el-table-column
prop="city"
label="市区"
width="120">
</el-table-column>
<el-table-column
prop="address"
label="地址"
width="300">
</el-table-column>
<el-table-column
prop="zip"
label="邮编"
width="120">
</el-table-column>
</el-table-column>
</el-table-column>
</el-table>
<el-button @click="exportExcel('文件名称')">导出</el-button>
</div>
</template>
<script>
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
export default {
name: 'project',
data() {
return {
tableData: [{
date: '2016-05-03',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-02',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-04',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-01',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-08',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-06',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-07',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}]
}
},
components: {
},
watch: {
},
methods: {
exportExcel(excelName) {
try {
const $e = this.$refs['report-table'].$el
let $table = $e.querySelector('.el-table__fixed')
if(!$table) {
$table = $e
}
const wb = XLSX.utils.table_to_book($table, {raw:true})
const wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST:true, type: 'array'})
FileSaver.saveAs(
new Blob([wbout],{type: 'application/octet-stream'}),
`${excelName}.xlsx`,
)
} catch (e) {
if (typeof console !== 'undefined') console.error(e)
}
}
},
mounted () {
}
}
</script>
<style>
</style>
效果如下:
本文转载自: https://blog.csdn.net/qq_47945175/article/details/131551277
版权归原作者 念茶辞 所有, 如有侵权,请联系我们删除。
版权归原作者 念茶辞 所有, 如有侵权,请联系我们删除。