一、通过 el-upload 上传组件选取文件

	<el-upload
    class="upload-demo" ref="upload" accept=".xls,.xlsx"
    action="https://localhost:8080/posts/"
    :on-change="upload"
    :show-file-list="false"
    :auto-upload="false"
    >
      <el-button slot="trigger" size="large">导入excel</el-button>
    </el-upload>
 	upload (file, fileList) {
      const files = { 0: file.raw }// 取到File
      this.readExcel(files)
    },
    readExcel (files) { // 表格导入
      if (files.length <= 0) { // 如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确,请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()
      fileReader.onload = (files) => {
        try {
          const data = files.target.result
          const workbook = xlsx.read(data, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0]// 取第一张表
          const ws = xlsx.utils.sheet_to_json(workbook.Sheets[wsname])// 生成json表格内容
          console.log(ws, 'ws是表格里的数据,且是json格式')
          this.menuData = ws
          // 重写数据
          this.$refs.upload.value = ''
          // return ws
        } catch (e) {
          console.log(e)
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },

二、通过 aixos 直接读取本地excel文件

获取本地文件信息,因为xlsx是后端访问的,所以需要用aixos请求去得到获取后的数据。文件需要放在public目录中,url: /menu.xlsx
在这里插入图片描述

main.js 文件中定义本地服务路径

在这里插入图片描述

读取并解析 excel 文件内容
	async readExcelFile (url) {
      await this.$http.get(url, { responseType: 'arraybuffer' })
        .then((res) => {
          const data = new Uint8Array(res.data)
          const wb = xlsx.read(data, { type: 'array' })
          const sheets = wb.Sheets // 获取文档数据
          this.content = this.transformSheets(sheets)
        }).catch(err => {
          this.err = err
        })
    },
    transformSheets (sheets) {
      const content1 = []
      const tmplist = []
      for (const key in sheets) {
        tmplist.push(xlsx.utils.sheet_to_json(sheets[key]).length)
        content1.push(xlsx.utils.sheet_to_json(sheets[key]))
      }
      console.log(tmplist)
      console.log(content1)
    },
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐