Vue中excel导入与导出的实现

116 阅读1分钟

一、Excel导入

1.组件定义

        <el-upload
        action=""
        accept=".xls,.XLS,.xlsx,.XLSX"
        :http-request="httpRequest"
        :show-file-list="false">
           <el-button size="mini" type="primary" @click="documentImport">文档导入</el-button>
        </el-upload>

其中http-request 覆盖默认的上传行为,可以自定义上传的实现

2. import XLSX from 'xlsx'

   httpRequest(e) {
    const file = e.file // 文件信息
    if (!file) {
      return false
    } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
      // 格式根据自己需求定义
      this.$message.error('上传格式不正确,请上传xls或者xlsx格式')
      return false
    }
    const fileReader = new FileReader()
    fileReader.onload = (ev) => {
      try {
        const data = ev.target.result
        const workbook = XLSX.read(data, {

          // 以字符编码的方式解析
          type: 'binary'
        })

        const exlname = workbook.SheetNames[0]
        const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]) // 生成json表格内容
        //对json表格内容进行初步判断
        try {
          exl.forEach((item, index) => {
            if (item.表地址 === undefined) {
              this.$set(item, '表地址', '')
            }
            if (item.户号 === undefined) {
              this.$set(item, '户号', '')
            }
            this.$set(item, 'rowcount', index + 1)
          }
          )
        } catch (e) {
          return false
        }
        //全局替换表头字段,得到需要的数据格式
          // 字符转换,将文字表头转换为对应的字段 this.excelCol为字段对应表 title key
            let getOutString = JSON.stringify(exl)
            this.excelCol.forEach((item) => {
              const escapedTitle = item.title.replace(
                /[.*+?^${}()|[\]\\]/g,
                '\\$&'
              )
              const str = new RegExp(escapedTitle, 'g')
              getOutString = getOutString.replace(str, item.key)
            })
            const getOutParse = JSON.parse(getOutString)
      } catch (e) {
        console.log('error')
        return false
      }
    }
    //readAsBinaryString() 方法用于启动读取指定的File 内容
    fileReader.readAsBinaryString(file)
  },

二、Excel导出(用js插件table2excel)

1.import table2excel from '@/common/utils/table2xlsx.js'

      const column = [
        {
          title: '时间',
          key: 'Time',
          type: 'text'
        },
        {
          title: '读数',
          key: 'data'
        },
        {
          title: '图片',
          key: 'imagePath',
          type: 'image',
          width: 200,
          height: 100
        }
      ]
      table2excel(column, this.tableData, '测试数据表单')