excel 的导入与导出

145 阅读2分钟

R-C.jpg

excel 的导入与导出

excel导入功能需要使用npm包**xlsx,所以需要安装xlsx**插件 (new FileReader() 选中了某个文件, 可以通过FileReader去读)

$ yarn add xlsx
<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
// 省略全局组件得到注册这里直接使用
export default {
  name: 'Import',
  methods: {
    handleSuccess({ header, results }) {
      // header 表头数据
      // results 需要的数据
      console.log(header)
      console.log(results)
    }
  }
}
</script>
// header中, results中的数据是中文的, 但是提交给后台的要是英文的
// 在这里准备一下对应关系
        const userRelations = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber'
        }
                const newArr = []
        results.forEach(item => {
          const obj = {}
          // item 每一个对象
          for (const k in item) {
          // userRelations[k] = timeOfEntry
            const englishKey = userRelations[k]
            // item[k] 每一项的值
            console.log(item[k])
            // obj[englishKey] 就是键
            if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
              obj[englishKey] = this.formatExcelDate(item[k], '-')
            } else {
              obj[englishKey] = item[k]
            }
          }
          newArr.push(obj)
        })
// 携带数据发送请求
await reqImportEmployee(newArr)
// 读取 excel 时间格式是以 : 1900-01-01 开始, 并且计算的是天数
// js 中时间戳: 1970-01-01 开始, 以毫秒为单位
// 这里是需要转换的时间
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }

需要注意一点就是下载的包是最新版本的问题有可能会有所不兼容的问题

// 导入的时候 
import XLSX from 'xlsx' // 错误
import * as XLSX from 'xlsx' // 正确
不然就会报一个错误 : Cannot read properties of undefined (reading 'read')

**批量导出 : **

// 资源懒加载
import('@/vendor/Export2Excel').then(async excel => {
        const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        const { data: { rows }} = await reqGetEmployeeList(1, this.total)
        const headersRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const arr = [] // 外面的大数组
        rows.forEach(item => {
          const newArr = [] // 里面的小数组
          headersArr.forEach(value => {
            const newData = headersRelations[value]
            if (newData === 'formOfEmployment') {
              // 导入的枚举处理聘用形式
              const userArr = employees.hireType.find(v => v.id === item[newData])
              const res = userArr ? userArr.value : '未知'
              newArr.push(res)
            } else {
              newArr.push(item[newData])
            }
          })
          arr.push(newArr)
        })
        console.log(arr)
        excel.export_json_to_excel({
          header: headersArr, // 表头
          data: arr, // 数据二维数组
          filename: '叼丝成名录', // 表名称
          autoWidth: true, // 宽度自适应
          bookType: 'xlsx' // 文件扩展名
        })
      })

复杂表头的导出

mutiHeader应该这样定义

 const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]

multiHeader中的一行表头中的字段的个数需要和真正的列数相等,假设想要跨列,多余的空间需要定义成空串

它主要对应的是标准的表头

 const header = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']

如果,我们要实现其合并的效果, 需要设定merges选项

  const merges = ['A1:A2', 'B1:F1', 'G1:G2']

merges的顺序是没关系的,只要配置这两个属性,就可以导出复杂表头的excel了