vue+element模板导入excel文件,生成对应的table

//因项目需求,在前端业务组,需要提供公共方法,就花了点时间研究
//1.使用直接复制整个文件
//需用在父页面引入使用模块
//调用方式
<ImportExcel  @changeExcl="changeExcl"  @closeExcl="closeExcl" @uploadExcl="uploadExcl" @downloadExcl="downloadExcl" :upload="upload" :downloadExclShow="downloadExclShow"/>

//组件代码
<template>
  <div class="feadFile">
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      :inline="true"
      width="1000px"
      class="dialog"
      :loading="loading"
      :before-close="closeExclPop"
      :modal-append-to-body="false"
    >
      <div class="import">
        <div class="file">
          <el-form ref="queryForm" label-position="top" label-width="68px">
            <div class="query-form-model">
              <el-form-item>
                <el-upload
                  ref="upload"
                  :limit="1"
                  accept=".xlsx, .xls"
                  :headers="upload.headers"
                  :action="upload.url"
                  :disabled="upload.isUploading"
                   :on-success="handleFileSuccess"
                  :auto-upload="false"
                  :on-change="importf"
                >
                  <el-button type="primary">选取文件</el-button>
                </el-upload>
                <!-- <input type="file" placeholder="请选择要上传的文件" @change="changeUpataExcl" /> -->
              </el-form-item>
              <el-form-item label>
                <el-button size="small" type="primary" @click="onSubmit">确认上传</el-button>
              </el-form-item>
              <el-form-item label v-if="downloadExclShow">
                <el-button size="small" type="primary" @click="downloadExclFunc()">下载模板</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <div class="el-table-view">
        <el-table :data="importData" v-if="tableShow">
          <template v-if="importData.length===0" slot="empty">
            <p class="table-no-data">
              <img src="@/assets/image/empty-table-bg.png" />
            </p>
          </template>
          <el-table-column
            v-for="(item , index) in importDataThead"
            :key="index"
            :prop="item"
            :label="item"
            width="150px"
          ></el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>
<script>

export default {
  name: "feadFile",
  data() {
    return {
      importData: [], //存储表格数据
      importDataThead: [],//存储表格

      upData: null, //存储读取excel文件
      tableShow: false, //没有导入成功前,table隐藏
      files: {}, //读取想用的上传文件内容
      file: {},
      loading:false,
    };
  },
  props: {  //监听父组件的传值
    
    updateExclShow: {
      //是否显示确认上传按钮
      type: Boolean,
      default: false
    },
    downloadExclShow: {
      //是否显示下载按钮
      type: Boolean,
      default: false
    },
    uploadExcl: {
      //确认上传
      type: Function,
      required: false
    },
    closeExcl: {
      type: Function,
      required: false
    },
    downloadExcl: {
      type: Function,
      required: false
    },
    changeExcl: {
      //上传按钮
      type: Function,
      required: false
    },
    
    upload: {
      type: Object,
      default: {}
    }
  },
  methods: {
    closeExclPop(done) {
      var _this = this;
      this.$emit("closeExcl");
      this.clearFilesFunc();
       _this.importData = [];
       _this.importDataThead = [];
       this.tableShow = false;
    },
    importf(obj, fileList) {
      var _this = this;
      var XLSX = require("xlsx");

      var files = event.currentTarget.files;
      var workbook; //读取完成的数据
      var fileReader = new FileReader();
      
        console.log(2);
        fileReader.onload = ev => {
          console.log(2);
          var data = ev.target.result;
          var workbook = XLSX.read(data, {
            type: "binary"
          });
          var persons = [];
          try {
          var data = ev.target.result;
          var workbook = XLSX.read(data, {
            type: "binary"
          });
          var persons = [];
        } catch (e) {
           this.msgError('文件类型不正确')
          return;
        }

          var fromTo = "";
          console.log("workbook", workbook);
          for (var sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
              fromTo = workbook.Sheets[sheet]["!ref"];
              persons = persons.concat(
                XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
              );
            }
          }
          console.log(persons)
          this.importDataThead = Array.from(Object.keys(persons[0])).map(
            item => {
              return item;
            }
          );

          this.importData = persons;
          console.log();
          this.tableShow = true;
          var data = {
            importDataThead: _this.importDataThead, //表头
            importData: _this.importData, //字段
            files: files //需要上传文件
          };
          this.$emit("changeExcl", data);
        };
      fileReader.readAsBinaryString(files[0]);
    },
    
    //上传excel
    onSubmit(e) {
      var _this = this;
      this.$refs.upload.submit();
       this.$emit("uploadExcl");
       _this.importData = [];
       _this.importDataThead = [];
       this.tableShow = false;
    
    },
    //下载模板
    downloadExclFunc() {
      this.$emit("downloadExcl");
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.loading = true
      console.log("上传中:", file);
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      var _this = this;
      console.log("上传成功:", response);
      if(response.code == 200){
          this.$message({
         message:'导入成功',
        type: "success",
        duration: 1500
     })
     _this.$emit("uploadExcl",response);
      }
      else{
        this.$message({
         message:response.msg,
        type: "error",
        duration: 1500
     })
      }
       this.loading = false
        
      this.clearFilesFunc(file)
    },
    //清空上传文件
    clearFilesFunc(file){
      console.log('清空:',file)
       this.$refs['upload'].clearFiles();
    }
  }
};
</script>
<style lang="scss" scoped>
// .dialog{
.el-dialog {
  padding: 20px 0;
  max-height: 400px;
  overflow: auto;
}
.el-table-view {
  height: 380px;
  margin-bottom: 10px;
  border: 1px solid #e6e6e6;
}
// }
</style>

你可能感兴趣的:(js常用案例,vue日常小知识,基础知识)