Vue上传Excel文件并校验Excel内容

版权声明:本文为博主原创文章,如有错误欢迎指正,如需转载请注明出处,谢谢配合。 https://blog.csdn.net/xiaxiangyun/article/details/88891484

背景

在近期开发的学校管理系统中,有一个导入管理模块,其中包含Excel的上传功能,由用户选择文件后进行上传,前端需要对文件内容进行初步校验后给出是否符合规范的提示后再传给后端。这就需要前端事先对Excel文件内容进行读取。
导入文件

解决

我们这个项目使用Vue+Typescript进行开发,UI库使用的是iView。在简单调研之后,我发现可以使用xlsx库实现对Excel文件内容的读取。下边放实现功能的关键部分代码。

<template>
  <Input style="width: 300px" readonly v-model="file.name"/>
  <Upload :before-upload="handleUpload" action accept=".xlsx">
    <Button v-if="hasFile" icon="ios-add" class="import_dash-button">添加文件</Button>
    <Button v-else class="import_dash-button">重新选择</Button>
  </Upload>
</template>

<script lang="ts">
import Vue from 'vue'
import XLSX from 'xlsx'
import { Component } from 'vue-property-decorator'
import { Input, Button, Upload } from '@xuexin/element'

const components = { Input, Button, Upload } as any
@Component({ name: 'ImportView', components })
export default class extends Vue {
  // Excel相关数据
  private outputs: any[] = []
  private readFlag: boolean = false
  private file: any = {}

  get hasFile (): boolean {
    return this.file.name === undefined ? true : false
  }

  /**
   * 选择上传文件
   */
  private handleUpload (file: any) {
    this.file = file
    this.readExcel(file)
    // 阻止自动上传
    return false
  }

  /**
   * 读取Excel文件
   */
  private readExcel (file: any) {
    this.readFlag = true
    const fileReader = new FileReader()
    fileReader.readAsBinaryString(file)
    fileReader.onload = (e: any) => {
      try {
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'binary' })
        // 取第一张表
        const wsname = workbook.SheetNames[0]
        // 生成json表格内容
        const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
        // 清空接收数据
        this.outputs = []
        // 添加表格数据
        for (let i = 0; i < ws.length; i++) {
          const item: any = ws[i]
          const sheetData: any = {
            address: item.addr,
            value: item.value
          }
          this.outputs.push(sheetData)
        }
      } catch (e) {
        return false
      }
    }
    this.readFlag = false
  }

  /**
   * 校验Excel内容
   */
  private checkExcel () {
	// TODO
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/xiaxiangyun/article/details/88891484