vue中如何将表格导入到页面 cv速成 有手就行!

2022-04-11 13:19:02

一、安装依赖包

节点版本安装了一个命令行工具xlsx,可以读取电子表格文件并以各种格式输出内容。源可在xlsx.njsbin 目录中找到。

npm install xlsx -S

二、引入UploadExcel组件并注册为全局

src/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">
      导入表格
      <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 {
  name: 'UploadExcel',
  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>

三、注册为全局组件

import UploadExcel from '@/components/UploadExcel/index.vue'

export default {
  install(Vue) {
    Vue.component(UploadExcel.name, UploadExcel)
  }
}

//在main.js导入并使用
// ...Vue.use(..)

四、在页面中使用组件

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

<script>
export default {
  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 }) {  //成功调用之后的函数
        //result,和header就是要对其进行操作的数据
        //results 是数据 header是表头(键)
      console.log(results, header)
    }
  }
}
</script>

这个组件引入了XLSX包, 需要给它提供两个props:
beforeUpload:上传之前的函数
onSuccess: 成功调用之后的函数

文件上传:是 本地硬盘 上传到 网页内存 (不是传给服务器)

  随便上传一个excel文件效果图

五、工作中的操作 (扩展,上面操作已完成)

工作中要比平常使用繁琐的多

1. 可能在新页面进行导入 (定义路由)

2.过程 表格导入到浏览器页面=》格式好后端服务器要的数据格式转换=》发送到后台服务器

使用场景

我们的excel表格中键是中文的 这时候就要进行转换 注意传过去的键一定要和接口文档一致,不能出现不对称

一、调用方法进行转换

 handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
+      const result = this.filter(results)
+      this.doImport(result)  //后面的操作进行发送ajax
    },

方便代码维护单独封装一个方法

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

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


 filter(result) {
        //定义要映射后的英文key
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
        // 找到数据中的每一项
      return result.map(obj => {  
        // 先定义英文key为空对象
        const newObj = {}
        // 去除中文的key
        const zhKeys = Object.keys(obj)
        // 找到所有中文key的每一项
        zhKeys.forEach(zhKey => {
          找到userRelations 里对应的英文key
          const enKey = userRelations[zhKey]
         // 由于当前时间值是ie中excel定义的值 需要转换
        //数据中 如果键等于 下面两个值 进行调用转换转换方法
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
         // 如果找到就进行替换添加到英文key对象中
            newObj[enKey] = new Date(formatExcelDate(obj[zhKey]))
          } else {
          //否则直接添加到英文key对象中
            newObj[enKey] = obj[zhKey]
          }
        })
        return newObj
      })
    }

 上面用到的日期处理函数在utils/index.js中定义如下

// 把excel文件中的日期格式的内容转回成标准时间
// https://blog.csdn.net/qq_15054679/article/details/107712966
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)
}

调用axios

 async doImport(result) {
      try {
        const res = await importEmployee(result)
        console.log('addStaffList', res)
        this.$message.success('导入成功')
        // 保存数据
        this.$router.back()
      } catch (err) {
        console.log('addStaffList', err)
        this.$message.error('失败')
      }
    },
  • 作者:奥特曼 
  • 原文链接:https://blog.csdn.net/m0_46846526/article/details/118383652
    更新时间:2022-04-11 13:19:02