五.Vue中Excel导入

144 阅读1分钟
<template>
  <div>
    <input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick">
    <div class="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
      Drop excel file here or
      <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
        Browse
      </el-button>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
export default {
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function// eslint-disable-line
  },
  data() {
    return {
      loading: false,
      excelData: {
        header: null,
        results: null
      }
    }
  },
  methods: {
    generateData({ header, results }) {
      this.excelData.header = header
      this.excelData.results = results
      this.onSuccess && this.onSuccess(this.excelData)
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('Only support uploading one file!')
        return
      }
      const rawFile = files[0] // only use files[0]
      if (!this.isExcel(rawFile)) {
        this.$message.error('Only supports upload .xlsx, .xls, .csv suffix files')
        return false
      }
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!rawFile) return
      this.upload(rawFile)
    },
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel
      if (!this.beforeUpload) {
        this.readerData(rawFile)
        return
      }
      const before = this.beforeUpload(rawFile)
      if (before) {
        this.readerData(rawFile)
      }
    },
    readerData(rawFile) {
      this.loading = true
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet)
          this.generateData({ header, results })
          this.loading = false
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    isExcel(file) {
      return /.(xlsx|xls|csv)$/.test(file.name)
    }
  }
}
</script>

<style scoped>
.excel-upload-input{
  display: none;
  z-index: -9999;
}
.drop{
  border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
</style>
复制代码
  • 我们需要安装一个实现Excel导入功能的插件xlxs
npm i xlsx | yarn add xlsx
复制代码
  • 将入导入功能封装成一个公共组件src/components/UploadExcel
  • 新建导入页面src/views/import/index.vue
<template>
  <!-- 公共导入组件 --> 
  <upload-excel :on-success="success" />
</template>
复制代码
  • 为导入页面配置路由
{
    path: '/import',
    component: Layout,
    hidden: true, // 隐藏在左侧菜单中
    children: [{
      path: '', // 二级路由path什么都不写 表示二级默认路由
      component: () => import('@/views/import')
    }]
  },
复制代码
  • 根据接口文档,封装一个导入Excel表格批量信息的接口
/** *
 *  封装一个导入员工的接口
 *
 * ***/

export function importEmployee(data) {
  return request({
    url: '/sys/user/batch',
    method: 'post',
    data
  })
}
复制代码

注意:本文章根据本人工作中的数据来实现,小伙伴要根据自己所属项目进行更改,文章中的案例是一个员工Excel表格的批量导入,仅供参考

  • 我们分析一下vue-element-admin为我们提供的代码中的逻辑

image.png 1、 输入框是一个file(文件上传类型的),并打了一个ref标识,定义change事件

注意:methods里面的逻辑比较复杂,所以我们只关心几个和核心方法,达到会用的目的即可

image.png 2、

  • 当我们点击上传文件按钮之后,handleUpload方法会调用文件上传框(file)的单机事件,随后我们可以选择要上传的Excel文件,选择好文件后,文件内容会上传的我们的文件上传框(file)中。
  • 因为我们在文件上传框(file)中定义了一个change事件,文件一上传就会触发handleClick事件,可以通过环境变量$event获取到我上传的文件,并将文件传参给我的upload方法
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!rawFile) return
      this.upload(rawFile)
复制代码
  • upload方法会通过refs获取到文件上传框,并清空内容,随后又经过判断将参数传递给readerData方法

image.png 3、readerData方法是实现Excel文件上传的核心,在这个方法里面我们有使用了js原生读取文件的构造函数FileReader,通过new FileReader, 我们得到一个实例对象,这时候,实例对象就可以配合我们最开始安装的xlsx插件,解析出我们Excel文件中的表头和表格内容【header、results】,并把两个数据传入到generateData方法中。

image.png

image.png 4、generateData方法里会将接收的【header、results】数据添加到data中excelData对象里面去。由于我们的上传Excel导入功能单独封装了一个组件,它是挂在Excel导入页面里面的,我们在导入页面会给我们的导入页面传递一个success方法来获取excelData对象

image.png

image.png

  • 父组件通过excelData对象中的数据后要进行处理,以下是我们需要导入的数据 image.png
  • results里的数据是对象形式的数组,对象里面的key值是汉字的形式,而服务器的请求数据必须是英文的才可以,所以我们要对数据进行处理,改变key值
async  success({ header, results }) {
      // 如果是导入员工
        const userRelations = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber'
        }
        const arr = []
       results.forEach(item => {
          const userInfo = {}
          Object.keys(item).forEach(key => {
            userInfo[userRelations[key]] = item[key]
          })
         arr.push(userInfo) 
        })
        await importEmployee(arr) // 调用导入接口
        this.$router.back()
    }
复制代码
  • 我们先定义了一个用于替换key值得对象,然后使用双层循环,实现了对数组中对象key值的修改,随后调用接口并返回业务页面

总结:Excel导入功能是我们情断开发中常用的的一个功能,本文章只是粗略的介绍用法,想深入研究的小伙伴可以去gitee上拉去‘花裤衩’的代码仔细研究,也可以找教学视频学习