vue + elementui 读取excel文件内容

需要先安装xlsx,  npm install xlsx -S

 

<template>
  <div class="content">
    <el-upload
      class="upload-demo"
      :on-change="handleChange"
      :show-file-list="false"
      :auto-upload="false"
    >
      <el-button size="small" type="primary" style="margin-bottom:15px;"
        >读取excel文件</el-button
      >
    </el-upload>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="Id" width="180"></el-table-column>
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="number" label="数量" width="180"></el-table-column>
    </el-table>
  </div>
</template>
<script>
import * as XLSX from 'xlsx'
export default {
  data() {
    return {
      tableData: [],
      fileContent: "",
      file: "",
      data: "",
    };
  },
  
  methods: {
    // 核心部分代码(handleChange 和 importfile)
    handleChange(file) {
      console.log(file);
      this.fileContent = file.raw;
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
      if (this.fileContent) {
        if (fileType === "xlsx" || fileType === "xls") {
          this.importfile(this.fileContent);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误,请重新上传!"
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件!"
        });
      }
    },
    importfile(obj) {
      console.log(obj);
      const reader = new FileReader();
      let _this = this;
      reader.readAsArrayBuffer(obj);
      reader.onload = function() {
        const buffer = reader.result;
        const bytes = new Uint8Array(buffer);
        const length = bytes.byteLength;
        let binary = "";
        for (let i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i]);
        }
        const wb = XLSX.read(binary, {
          type: "binary"
        });
        const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); // 默认第一行下为空也能解析出第一四行
        this.data = [...outdata];
        const arr = [];
        this.data.map(v => {
          const obj = {};

          obj.name = v.name;
          obj.id = v.id;
          obj.number = v.number;
          console.log(obj);
          arr.push(obj);
        });
        _this.tableData = _this.tableData.concat(arr);
      };
    },
  }
};
</script>
<style lang="less" scoped>

</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值