vue中导入excel/图片

156 阅读1分钟

依赖

npm install xlsx

dom

<template>
  <div class='test_container'>
    <el-card>
      <input
        type="file"
        ref="input1"
        accept=".png,.jpg"
        @change='handleChange'>
      <input
        type="file"
        ref="input2"
        accept=".xlsx, .xls"
        @change='handleChange'>
      <el-button @click="upload(0)">上传图片</el-button>
      <el-button @click="upload(1)" :loading='loading'>上传excel</el-button>
      <div class="show">
        <p>图片展示区域</p>
        <img width="200" :src="src" alt="">
        <p>上传的excel展示区域</p>
        <el-table
          :data="result"
          style="width: 100%"
          border
          stripe
          id="table"
          ref="table"
          v-show="result.length > 0">
          <el-table-column
            v-for="item in header"
            :key="item"
            :prop="item"
            :label="item">
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

js

<script>
import * as XLSX from 'xlsx'
export default {
  name: 'test',
  data () {
    return {
      src: '',
      uploadLimit: 1,
      loading: false,
      result: [],
      header: []
    }
  },
  created () {
    console.log(XLSX)
  },
  methods: {
    upload (val) {
      if (val === 0) {
        this.$refs.input1.click()
        return
      }
      this.$refs.input2.click()
    },
    handleChange (e) {
      const files = e.target.files[0]
      // 判断类型
      const fileType = this.judgeType(files)
      if (fileType === 'isImage') {
        // 处理图片文件
        this.handleImage(files)
      } else if (fileType === 'isExcel') {
        // 处理excel文件资源
        this.handleExecl(files)
      }
    },
    judgeType (file) {
      const imageReg = /\.(png|jpg)$/
      const excelReg = /\.(xlsx|xls|csv)$/
      if (imageReg.test(file.name)) return 'isImage'
      if (excelReg.test(file.name)) return 'isExcel'
      throw new Error('file type is not image/excel!')
    },
    handleImage (file) {
      // 判断上传大小
      if (!this.beforeUpload(file.size)) return

      const form = new FormData()
      form.append('file',file)
      // 将form传到后端
      this.src = URL.createObjectURL(file)
    },
    handleExecl (file) {
      console.log(file)
      // 判断上传大小
      if (!this.beforeUpload(file.size)) return
      this.readerData(file)
    },
    beforeUpload (size) {
      const mb = size / 1024/ 1024
      const isLimit = mb < 1

      if (isLimit) {
        return true
      }
      this.$message.warning(`Please do not up upload larger than ${this.uploadLimit} M`)
      return false
    },
    readerData (rawFile) {
      this.loading = true
      // 处理并获取数据
      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]
        this.header = this.getHeaderRow(worksheet) // 获取表头 ['id', 'title', 'name', 'age']
        /**
         * result:
         *        [
         *          {id: 1, title: 2, name: 3, age: 4, __rowNum__: 1}
         *        ]
         */
        this.result = XLSX.utils.sheet_to_json(worksheet)
        this.loading = true
      }
      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
    }
  }
}
</script>