最近需要一个组件将接口返回的数据导出为Excel,将实现过程记录一下,并进行封装,以达到开箱即用,节省开发时间。
首先安装依赖
npm i file-saver --save
npm i xlsx --save
npm i script-loader --save
使用组件
/**
* @Author: 858834013@qq.com
* @Name: exportExcel
* @Date: 2022-08-20
* @Desc: 导出文档
*/
<template>
<div class="newButton">
<exportExcel :t-header="header" :key-val="keyVal" :list="list" file-name="导出demo">
<el-button type="primary">导出Excel</el-button>
</exportExcel>
</div>
</template>
<script>
import exportExcel from "./exportExcel";
export default {
name: "demo",
components: {
exportExcel,
},
data: function () {
return {
header: ['标题', '描述', '内容'],
keyVal: ['title', 'desc', 'content'],
list: [{
title: '这是标题',
desc: '这是描述',
content: '这是内容'
}, {
title: '标题',
desc: '描述',
content: '内容'
},]
}
},
mounted() {
},
methods: {},
}
</script>
<style lang="less">
.newButton {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: nowrap;
flex-direction: row;
padding-top: 200px;
}
</style>
组件封装
/**
* @Author: 858834013@qq.com
* @Name: exportExcel
* @Date: 2022-08-20
* @Desc: 导出Excel
*/
<template>
<div @click="export2Excel">
<slot></slot>
</div>
</template>
<script>
import {export_json_to_excel} from "./utils/Export2Excel";
export default {
name: "exportExcel",
data: function () {
return {}
},
props: {
// 表头内容
tHeader: {
type: Array,
default() {
return ['标题', '内容']
}
},
//对应表头的键名
keyVal: {
type: Array,
default() {
return ['title', 'content']
}
},
// 数据内容
list: {
type: Array,
default() {
return [{
title: '',
content: ''
}]
}
},
// 文件名称
fileName: {
type: String,
default() {
return 'excel'
}
},
},
mounted() {
},
methods: {
formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => v[j]))
},
export2Excel() {
var that = this;
that.$message({
message: '正在准备数据中',
type: 'warning'
})
require.ensure([], async () => {
export_json_to_excel(that.tHeader, that.formatJson(that.keyVal, that.list), that.fileName)
})
},
},
}
</script>