如何在vue中导出Excel文件

353 阅读1分钟

导出

1 功能介绍

前端主导

image.png 后端主导

image.png

2 导出

复制vue-element-admin中提供的导出功能

panjiachen.github.io/vue-element…

image.png

安装依赖

npm install file-saver script-loader xlsx --save

按需引入

等什么时候需要直接注册使用就行

import('@/vendor/Export2Excel').then(excel => {})

3 示例 ( 员工导出 )

3.1 思路

image.png

3.2 最终代码

import('@/vendor/Export2Excel').then(async execl => {
        const res = await getEmployees(this.pageParams.page, this.pageParams.size)
        const list = res.data.rows
        // console.log(list)
        const { header, data } = this.formData(list)
        execl.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })

3.3 转换数据

image.png

 formData(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const hireType = EmployeeEnum.hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})
      let header = [] // 表头数据
      let data = []
      const first = list[0]
      if (!first) {
        return { header, data }
      }
      header = Object.keys(first).map(key => {
        return mapInfo[key]
      })
      data = list.map(obj => {
        const key = obj['formOfEmployment']
        obj['formOfEmployment'] = hireType[key]
        return Object.values(obj)
      })
      return { header, data }
    },

3.4 hireType数据转换

image.png