如何在项目中复用 “导入Excel”(备忘)

安装插件:

npm install xlsx -S
复制代码

在项目src/components/UploadExcel中导入与其对应的文件

[gitee.com/MeQgJ/human…]

image.png

之后可以按照需求将其导入为全局组件或局部组件

这里以全局组件为例

import PageTools from './PageTools'
import UploadExcel from './UploadExcel'

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

在自己项目中所需要的地方使用这个组件

<UploadExcel 
:on-success="handleSuccess" 
:before-upload="beforeUpload" 
/>

methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
    }
  }
复制代码

配置好路由之后,根据自己的需求将Excel表格中的数据改成自己需要的格式,上传给后台数据库

在handleSuccess回调中写入自己的代码根据需求更改即可

handleSuccess({ results, header }) {
      const data = this.transExcel(results)
      this.doImport(data)
      this.$router.back()
    },
    // 把一个对象数组中的每一个对象的属性名,从中文改成英文
    // 思路:对于原数组每个对象来说
    // 1. 找出所有的中文key
    // 2. 找得到对应的英文key
    // 3. 拼接一个新对象:英文key:值
    transExcel(results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(item => {
        const obj = {}
        // 1. 取出这个对象所有的属性名: ['姓名', ‘手机号’]
        // 2. 遍历这个数组,通过 中文名去 userRelations 找对应英文名, 保存值
        const zhKeys = Object.keys(item)
        zhKeys.forEach(zhKey => {
          const enKey = userRelations[zhKey]
          // 如果是时间格式,就要做转换
          if (enKey === 'correctionTime' || enKey === 'timeOfEntry') {
            obj[enKey] = new Date(formatExcelDate(item[zhKey]))
          } else {
            obj[enKey] = item[zhKey]
          }
        })

        return obj
      })
    }
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享