Vue中实现excel导入导出功能

805 阅读2分钟

前言

  • 后端需要提供一个Excel模板文件 用户填写了这个Excel模板文件 上传这个文件就可以实现了

导入

第一步:分析vue-admin-element中的方案

图一.png

第二步 预览

2.png

安装xlsx包 并定义

yarn add xlsx

定义组件

import XLSX from 'xlsx'

export default {
  props: {
    beforeUpload: Function,    // 上传之前的函数
    onSuccess: Function       //  成功调用之后的函数
  }
}

使用组件

// 引用上边定义的组件,并传入两个属性
<upload-excel-component 
      :on-success="handleSuccess" 
      :before-upload="beforeUpload" 
    />

核心代码区

methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: '请不要上传大小超过1m的文件',
        type: 'warning'
      })
      return false
    },
  }

处理Excel导入的数据处理

  • 中文转英文:excel中读入的是姓名,而后端需要的是username

  • 日期处理:从excel中读入的时间是一个number值,而后端需要的是标准日期。

  //中文转英文
   methods: {
    async handleSuccess({ results, header }) {
      // results 表体  header 表头
      const Info = {
        日期: 'timeDate',
        手机号: 'mobile',
        姓名: 'username',
      }
      var newResult = results.map((item) => {
        // 定义一个空对象.重新定义 数组中的每一项
        var obj = {}
        // 获取中文键数组
        var ChineseKeys = Object.keys(mapInfo)
        ChineseKeys.forEach((key) => {
          // 获取中文键对应的英文值
          var enKey = Info[key]
          // 重新定义数组中每一项的值
          // obj[enKey] = item[key]
          // 解决execl时间转换问题
          if (enKey === 'timeDate') {
            obj[enKey] = new Date(formatExcelDate(item[key]))  //formatExcelDate函数封装如下
          } else {
            obj[enKey] = item[key]
          }
        })
        return obj
      })
      // importEmployee === 导入excel的请求接口
      const res = await importEmployee(newResult)
      console.log(res)
    }
  }

把Excel中的文件中的如期格式转换成标准的时间

用1970-1-1 减去1900-1-1 得到相差的 中间相隔70年

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)
  )
}

导出功能

借助vue-element-admin 现有的模板 复制粘贴

图5.png

在组件上使用如下代码

<template #right>
    <el-button size="small" type="primary" @click="handleDownload">导出
</el-button>
</template>

核心代码

        // 导出
    handleDownload() {
        // 打开Dialog 弹出一个对话框
      this.downloadLoading = true
        // 导入的文件 @/vendor/Export2Excel 
      import('@/vendor/Export2Excel').then(async excel => {
        // 导出的数据列表
        // const list = this.tableData
        // 导出所有的数据
        const res = await getEmployeeList({ page: 1, size: this.total })
        const list = res.data.rows
        // 处理之后返回的excel列表  data是一个二维数组
        // formmatJson===处理list数据 将数据转成二维数组 返回使用data接收
        const data = this.formatJson(list)
        const tHeader = this.header
        excel.export_json_to_excel({
          // 设置多表头
          multiHeader: [
            ['前端72期']
          ],
          // 合并列
          merges: ['A1:J1'],
          // 设置表格中的表头
          header: tHeader,
          data: data,
          filename: this.filename, // 设置文件名
          autoWidth: true, // 设置表格宽度
          // 设置文件格式 默认是xlsx
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(list) {
      const map = {
        'id': '编号',
        'mobile': '手机号',
        'username': '姓名',
        'timeData': '日期',
      }
        // 将list数组转换成二维数组
      return list.map(item => {
        // 定义一个收集数据的对象
        var obj = {}
        // 根据需求筛选出想要的数据
        var enkey = Object.keys(map)
        // 获取每一个英文键所对应的值
        enkey.forEach(key => {
          // 获取中文键
          var zhKey = map[key]
          // 将英文键赋值给中文键
          obj[zhKey] = item[key]
        })
        // 获取所有的值
        var newArr = Object.values(obj)
        // 获取中文键  设置表头
        this.header = Object.keys(obj)
        return newArr
      })
    }

注意点:Export2Excel依赖的包有js-xlsxfile-saverscript-loader需要安装

导入的文件 @/vendor/Export2Excel 可以自行下载 *

222.png

ps:不知道怎么下载Export2Excel文件的 可以私我发资料包

`有问题欢迎指出哦 大家一起进步`

353B4EE1.png