excel导出功能介绍
背景
在表格(element-table)中查询到了我们需要的数据,希望用他们生成excel文件,保存在本地。
1
使用现成的excel导出组件
1-1 首先下载依赖的包 js-xlsx
、file-saver
和script-loader
npm install file-saver script-loader xlsx --save
2.将vue-element-admin中的src/vendor/export2Excel复制到本项目中,直接使用 (没有文件的伙伴请一键三连,我会好好感谢的,懂得都懂)
3.给导出excel按钮绑定点击事件,在事件中抄这段代码就欧克了
import('@/vendor/Export2Excel').then(excel => {
// excel表示导入的模块对象
console.log(excel)
excel.export_json_to_excel({
header: ['姓名', '工资'], // 表头 必填
data: [
['刘备', 100],
['关羽', 500]
], // 具体数据 必填
filename: 'excel-list', // 文件名称
autoWidth: true, // 宽度是否自适应
bookType: 'xlsx' // 生成的文件类型
})
})
注意:这是最基础的excel导出 实际开发中 要使用业务真实数据实现导出功能
准备表头header数据
因为接口中返回的数据中的key是英文,而我们期望导出的表头是中文,所以提前准备中文和英文的映射关系
const map = {
'id': '编号',
'password': '密码',
'mobile': '手机号',
'username': '姓名',
'timeOfEntry': '入职日期',
'formOfEmployment': '聘用形式',
'correctionTime': '转正日期',
'workNumber': '工号',
'departmentName': '部门',
'staffPhoto': '头像地址'
}
目标表格data数据
具体的表格数据我们需要通过接口从后端获取回来,难点在于如何把后端返回的数据处理成
Export2Excel
插件需求的二维数组格式。
补充一个用来处理数据的函数
// 封装一个转换格式的函数
formatDate(rows) {
const map = {
'id': '编号',
'mobile': '手机号',
'username': '姓名',
'password': '密码',
'timeOfEntry': '入职日期',
'formOfEmployment': '聘用形式',
'workNumber': '工号',
'correctionTime': '转正日期',
'departmentName': '部门',
'staffPhoto': '头像地址'
}
// header = ['id', 'mobile', 'username', .....]
// data = [
// ['65c2', '1380000002', '管理员', ....],
// ['65c3', '1380000003', '孙财', ....],
// ]
// 把请求回来的数据中的第一条数据的K值取出来
const enkeys = Object.keys(map)
const header = enkeys.map(enkey => map[enkey])
const data = rows.map(obj => {
return Object.values(obj)
})
console.log(enkeys, header, data)
return {
header,
data
}
},
最终的代码
// 导出excel
async hExportExcel() {
// 1. 先向服务器请求最新的数据
const res = await getRoles(this.paramsPage)
console.log('最新的员工数据', res.data.rows)
const { header, data } = this.formatDate(res.data.rows)
console.log('结果', header, data)
import('@/vendor/Export2Excel').then(excel => {
// excel表示导入的模块对象
console.log(excel)
excel.export_json_to_excel({
header: header, // 表头 必填
data: data, // 具体数据 必填
filename: 'excel-list', // 文件名称
autoWidth: true, // 宽度是否自适应
bookType: 'xlsx' // 生成的文件类型
})
})
}