需要先安装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>

GitHub 加速计划 / eleme / element
54.06 K
14.63 K
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:3 个月前 )
c345bb45 7 个月前
a07f3a59 * Update transition.md * Update table.md * Update transition.md * Update table.md * Update transition.md * Update table.md * Update table.md * Update transition.md * Update popover.md 7 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐