如何在vue中导入Excel文件

673 阅读1分钟

导入

1 安装必要的插件

npm install xlsx -S

2 引入UploadExcel组件并注册为全局

将vue-element-admin提供的组件复制到自己的项目src/components/UploadExcel
panjiachen.github.io/vue-element…
github.com/PanJiaChen/…
components/index.js中注册成全局组件

...
import UploadExcel from './UploadExcel'

export default {
  // 插件的初始化, 插件给你提供的全局的功能, 都可以在这里配置
  install(Vue) {
    // 进行组件的全局注册
    ...
    Vue.component('UploadExcel', UploadExcel) // 注册导入excel组件
  }
}

3 配置路由 + 新建Import组件

import组件

<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
export default {
  name: 'Import',
  methods: {
    handleSuccess({ header, results }) {
      console.log(header, results)
    }
  }
}
</script>

配置路由

{
    path: '/import',
    component: '...',
    hidden: true, // 不显示到左侧菜单
    children: [{
      path: '', 
      component: () => import('@...')
    }]
}

4 测试组件效果

image.png

5 导入Excel ( 示例:员工信息 )

5.1 封装接口

export function importEmployee(data) {
  return request({
    ...
  })
}

5.2 数据转换

image.png

// 思路:对于原数组每个对象来说
//    (1) 找出所有的中文key
//     (2)  得到对应的英文key
//     (3)  拼接一个新对象: 英文key:值
 transExecl(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return data.map(oldObj => {
        const newObj = {}
        const oldKeys = Object.keys(oldObj)
        oldKeys.forEach(oldKey => {
          const newKey = mapInfo[oldKey]
          if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
            newObj[newKey] = new Date(formatExcelDate(oldObj[oldKey]))
          }
          newObj[newKey] = oldObj[oldKey]
        })
        return newObj
      })
    }

5.3 时间转换

image.png

export function formatExcelDate(numb, format = '/') {
  const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
  time.setYear(time.getFullYear())
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}

5.4 在页面中使用

methods:{
  ...
  // 把数据从excel文件读入到浏览器内存
  handleSuccess({ header, results }) {
    // console.log(header, results)
    // console.log(this.transExecl(results))
    this.doImport(this.transExecl(results))
  },
  async doImport(data) {
    try {
      await importExcel(data)
      this.$router.back()
    } catch (error) {
      console.log(error)
    }
  }
}