Vue

Vue 导入Excel文件并展示数据

2022-08-24  本文已影响0人  Charles2018

插件

yarn add xlsx

代码

<template>
  <div class="importExample">
    <el-upload
      class="upload-demo"
        action=""
        drag
        ref="upload"
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        :file-list="fileList"
        :on-change="onUploadHandleChange"
        :show-file-list="false"
        :auto-upload="false">
        <i class="el-icon-upload"/>
        <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        <div class="el-upload__tip"><span style="color:red;font-weight:800;">请上传 .xls / .xlsx 格式文件</span></div>
      </el-upload>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="180"></el-table-column>
    </el-table>
  </div>
</template>
<script>
export default{
  name: 'ImportExample',
  data() {
      return{
          fileList:[],
          tableData:[],
      }
  },
  methods:{
    onUploadHandleChange(file){
        const _this = this
        _this.tableData = []
        const fileName = file.name;
        const reader = new FileReader();
        //提取excel中文件内容
        reader.readAsArrayBuffer(file.raw);
        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 XLSX = require("xlsx");
          //转换二进制
          const wb = XLSX.read(binary, {
              type: "binary",
          });
          const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          outdata.forEach((i) => {
            let obj = {
                name: i.姓名,
                phone: i.手机号,
            };
            _this.tableData.push(obj)
          });
        };
    },
  }
}
</script>

预览

image
上一篇 下一篇

猜你喜欢

热点阅读