优雅的Excel导入导出

1,080 阅读2分钟

前言

在后管系统中,Excel导入导出功能是必备的,使用非常频繁,该如何现实?此时作为前端的你我是不是想到后端来完成,是个好想法🤣,大可不必要!⬇️⬇️⬇️看

思路与方案

  1. 前端主导

    1.1[导入]上传excel文件,把excel文件的内容读出来,还原成最基本的行列结构,按后端的接口文档要求回传过去。

    1.2[导出] 向请求事件数据,处理后端返回的数据,生成excel文件.xlsx

  2. 后端主导

    2.1[导入] 前端调接口传excel文件,后端收到文件处理保存到数据库

    2.2[导出] 前端调接口,后端返回excel文件.xlsx

导入实现

注意下包 npm install xlsx@0.14.1 -S
首先创建ImportExcel.vue父组件 和 UploadExcel/index.vue子组件,在父组导入子组件使用子组件

员工导入实例 image.png

  1. 读出来的excel的内容: 13299760077448072.gif
  2. 按后端接口文档,处理读出来的excel的内容

13299760852392532.gif 实现代码

  1. ImportExcel.vue
<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <UploadExcel
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
        />
      </el-card>
    </div>
  </div>
</template>

<script>
import UploadExcel from '@/components/UploadExcel/index'
import { formatExcelDate } from '@/utils'
import { abatchEmployessAPI } from '@/api/employees'
export default {
  components: { UploadExcel },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  }, methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: '请勿上传超过1m大小的文件',
        type: 'warning'
      })
      return false
    },

    async  handleSuccess({ results, header }) {
      console.log('读出来的excel的内容是', results, header)
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      // 按后端接口文档,处理读出来的excel的内容
      const abatchForm = results.map(item => {
        const obj = {}
        const keycont = Object.keys(item)
        keycont.forEach(ele => {
          const enkey = mapInfo[ele]
          if (enkey === 'correctionTime' || enkey === 'timeOfEntry') {
            obj[enkey] = new Date(formatExcelDate(item[ele]))
          } else {
            obj[enkey] = item[ele]
          }
        })
        return obj
      })
      const res = await abatchEmployessAPI(abatchForm)
      if (res.message === 10000) {
        this.$message(res.methods)
      }
    }
  }
}
</script>

  1. UploadExcel/index.vue
<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">
      将excel文件放到这里或
      <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
        浏览
      </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] // 只使用文件[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] // 只使用文件[0]
      if (!rawFile) return
      this.upload(rawFile)
    },
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // 修复不能选择相同的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
      /* 从第一行开始*/
      for (C = range.s.c; C <= range.e.c; ++C) { /* 走每一列的范围 */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- 替换为所需的默认值
        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>


导出实现

安装依赖: npm install file-saver script-loader xlsx --save

import('@/vendor/Export2Excel').then(excel => {
  // excel表示导入的模块对象
  console.log(excel)
  excel.export_json_to_excel({
    header: ['姓名', '工资'], // 表头 必填
    data: [
      ['刘备', 100],
      ['关羽', 500]
    ], // 具体数据 必填
    filename: 'excel-list', // 文件名称
    autoWidth: true, // 宽度是否自适应
    bookType: 'xlsx' // 生成的文件类型
  })
})

以上代码表示:

  1. 当我们正式点击导出按钮之后,才去加载vendor文件夹中的Export2Excel模块
  2. import方法执行完毕返回的是一个promise对象,在then方法中我们可以拿到使用的模块对象
  3. 重点关注data的配置部分,我们发现它需要一个严格的二维数组 参数 | 说明 | 类型 | 可选值 | 默认值 | | --------- | ----------- | ------- | ----------------------------------------------------------------------------------- | ---------- | | header | 导出数据的表头 | Array | / | [] | | data | 导出的具体数据 | Array | / | [[]] | | filename | 导出文件名 | String | / | excel-list | | autoWidth | 单元格是否要自适应宽度 | Boolean | true / false | true | | bookType | 导出文件类型 | String | xlsx, csv, txt, more | xlsx

Export2Excel代码

结束语

此文的目的是如何使用vue-element-admin的Excel导入导出
Excel导入导出功能不管是前端做还是后端做,都不是轻松的,在实际开发中为了节省时间,会选择面向对象完成此功能,最后再说一句我是前端菜鸟😁