前端主导(工作大量在前端)
vue-element-admin中的导出方案
1.把vue-element-admin中的导出功能,迁移本项目
2.在项目中安装依赖 npm install file-saver script-loader xlsx --save
3.给导出按钮添加点击事件
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' // 生成的文件类型
})
})
以上代码表示:
-
当我们正式点击
导出
按钮之后,才去加载vendor文件夹中的Export2Excel模块 -
import方法执行完毕返回的是一个promise对象,在then方法中我们可以拿到使用的模块对象
-
重点关注data的配置部分,我们发现它需要一个严格的二维数组
-
Excel导出参数说明
参数 说明 类型 可选值 默认值 header 导出数据的表头 Array / [] data 导出的具体数据 Array / [[]] filename 导出文件名 String / excel-list autoWidth 单元格是否要自适应宽度 Boolean true / false true bookType 导出文件类型 String xlsx, csv, txt, more xlsx - 案例
-
format(res) { const hmap = { 'id': '编号', 'password': '密码', 'mobile': '手机号', 'username': '姓名', 'timeOfEntry': '入职日期', 'formOfEmployment': '聘用形式', 'correctionTime': '转正日期', 'workNumber': '工号', 'departmentName': '部门', 'staffPhoto': '头像地址' } const header = Object.keys(res[0]).map(obj => hmap[obj]) const data = res.map(obj => Object.values(obj)) console.log(header, data) return { header, data } }, // 导出exclx功能 async hExport() { import('@/vendor/Export2Excel').then(async excel => { // 1.发ajax发请求拿请求 await this.loadEmployee() // 2.做数据格式转换 console.log(this.list) const { header, data } = this.format(this.list) excel.export_json_to_excel({ // header: ['姓名', '工资'], // 表头 必填 header: header, // 表头 必填 data: data, // data: [ // ['刘备11111111111111', 100], // ['关羽', 500] // ], // 具体数据 必填 filename: '员工信息' // 文件名称 }) }) }