vue 导入文件直接显示

先看效果图

QQ图片20200109095847.png

实现方法:xlsx

步骤:

1.首先安装xlsx组件
npm install xlsx --save
2.封装一个组件处理excel数据

<template>
  <span>
  <!-- 仅用于接收文件 不显示 display:none -->
    <input
      ref="excel-upload-input"
      class="excel-upload-input"
      type="file"
      accept=".xlsx, .xls"
      @change="handleClick"
    />
    <el-button @click="handleUpload">上传文件</el-button>
  </span>
</template>

<script>
import XLSX from "xlsx";
export default {
  props:{
    onSuccess:Function,//传入表格数据获取成功后方法
  },
  data(){
    return{
      excelData: {
        header: null, //表格头部
        results: null  //具体数据内容
      }
    }
  },
  methods: {
    //数据处理成功执行的方法
    generateData({ header, results }){
      this.excelData.header = header
      this.excelData.results = results
      this.onSuccess && this.onSuccess(this.excelData)
    },
    //点击上传按钮 调用input的点击事件
    handleUpload(){
      this.$refs['excel-upload-input'].click()
    },
    //input的点击事件
    handleClick(e) {
      const file = e.target.files;
      const rawFile = file[0];
      if (!rawFile) return;
      this.upload(rawFile);
    },
    //清空数据
    handleClear(){
      this.excelData = {
        header: [],
        results: []
      }
      this.onSuccess && this.onSuccess(this.excelData)
    },
     //导入表格
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // fix can't select the 
      this.readerData(rawFile);
    },
    //表格数据处理(重点)
    readerData(rawFile) {
      return new Promise((reslove, reject) => {
        const reader = new FileReader();
        reader.onload = e => {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: "array" });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const header = this.getHeaderRow(worksheet);
          const results = XLSX.utils.sheet_to_json(worksheet)
          this.generateData({ header, results })
          console.log(results)
        };
        reader.readAsArrayBuffer(rawFile);
      });
    },
    getHeaderRow(sheet) {
      const headers = [];
      const range = XLSX.utils.decode_range(sheet["!ref"]);
      let C;
      const R = range.s.r;
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    }
  }
};
</script>

<style scoped>
.excel-upload-input{
  display: none;
  z-index: -9999;
}
</style>

3.父组件调用

<template>
  <div class="upload-box">
    <upload-excel :on-success="handleSuccess"></upload-excel>
    <el-button @click="handleDownExcel">下载导入模板</el-button>
    <el-button @click="handleClear">清空数据</el-button>
    <p>已导入{{tableData.length}}条数据</p>
    <el-table border v-if="tableData.length" :data="tableData" size="mini" height="400">
      <el-table-column type="index" label="序号" :index="1" width="80" align="center"></el-table-column>
      <el-table-column
          v-for="item of tableHeader"
          :key="item"
          :prop="item"
          :label="item"
          align="center"
      ></el-table-column>
    </el-table>
  </div>
</template>

<script>
import UploadExcel from "@/components/UploadExcel";
export default {
  name: "",
  components: { UploadExcel },
  data() {
    return {
      tableHeader: [],
      tableData: [],
    };
  },
  methods: {
    // 下载
    handleDownExcel(type) {
      // console.log(type);
      const url = 'http://192.168.0.152:8104/util/downloadExcels?fileName='
      let excelUrl = "XXX.xls";
      window.open(url+excelUrl)
    },
    // 清空数据
    handleClear() {
      this.tableHeader = [];
      this.tableData = [];
    },
    //处理表格数据
    handleSuccess({ results, header }) {
      this.tableData = results;
      this.tableHeader = header;
    }
  }
};
</script>

至此数据直接展示就好了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ## 框架和库的区别?> 框架(framework):一套完整的软件设计架构和**解决方案**。> > 库(lib...
    Rui_bdad阅读 8,139评论 1 4
  • Vue-Music 一| 前期工作 1.项目初始化 npm install -g vue-cli vue init...
    noobakong阅读 5,830评论 0 5
  • 包含 react基础 react传值 react路由 和redux管理 和react-redux reactDom...
    栀璃鸢年_49a3阅读 4,853评论 0 1
  • python学习笔记 声明:学习笔记主要是根据廖雪峰官方网站python学习学习的,另外根据自己平时的积累进行修正...
    renyangfar阅读 8,229评论 0 10
  • 材料:纸,水溶性彩色铅笔
    西柠在简书阅读 1,768评论 0 5