Table数据导出到Excel

/ vue / 没有评论 / 182浏览

Environment

Element ui + Vue

Demo

NPM Install dependencies

$ npm  install  --save  xlsx  file-saver

Code

template

<template>
  <div>
  // 导出按钮部分
  ···
                  <el-col :span="3" >
                  <el-button type="info" icon="el-icon-download"  @click="exportExcel">导出表格</el-button>
                </el-col>
  ···
  // table 部分
          <el-table
          v-loading="loading"
          element-loading-text="🐱 喵~ 玩命加载中..."
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          :highlight-current-row=true
          :stripe=true
          :show-header=true
          :header-cell-style="{background:'#bfeeee',color:'#1b1f1e'}"
          :data="receiverInfos"
          id="table-id"
          style="width: auto">
  </div>
</template>

scripts

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
methods: {
      // 导出表格
    exportExcel() {
      //  table-id 要导出的是哪一个表格
      var wb = XLSX.utils.table_to_book(document.querySelector("#table-id"));
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "报表名称"+ ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
}
</script>