前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Element 表格导出为Excel表格

Element 表格导出为Excel表格

作者头像
tianyawhl
发布2019-12-03 14:32:59
2.7K0
发布2019-12-03 14:32:59
举报
文章被收录于专栏:前端之攻略

一、安装xlsx和filesaver

npm install --save xlsx file-saver

二、在表格组件中引入安装的2个文件

import FileSaver from "file-saver"; import XLSX from "xlsx";

三、HTML结构

代码语言:javascript
复制
    <el-table :data="tableData3" style="width: 500px" height="250" id="table">
      <el-table-column fixed prop="date" label="日期" width="150"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="province" label="省份" width="120"></el-table-column>
      <el-table-column prop="city" label="市区" width="120"></el-table-column>
      <el-table-column prop="address" label="地址" width="300"></el-table-column>
      <el-table-column prop="zip" label="邮编" width="120"></el-table-column>
    </el-table>
    <el-button type="success" style="margin-top:20px;" @click="exportExcel">导出</el-button>

 四、导出的方法

代码语言:javascript
复制
  methods: {
      exportExcel() {
          // out-table 关联导出的DOM节点
          var fixed = document.querySelector(".el-table__fixed");
          var excelTitle = "标题";
          var wb = XLSX.utils.table_to_book(document.querySelector("#table"));
          /* get binary string as output */
          var wbout = XLSX.write(wb, {
              bookType: "xlsx",
              bookSST: true,
              type: "array"
          });
          try {
              FileSaver.saveAs(
                  new Blob([wbout], { type: "application/octet-stream" }),
                  excelTitle + ".xlsx"
              );
          } catch (e) {
              if (typeof console !== "undefined") console.log(e, wbout);
          }
          return wbout;
      }
  }

在页面点击导出按钮时可以正常导出,但是如果左边有固定的列,相同的数据会导出2遍,可以做如下修改:

代码语言:javascript
复制
  methods: {
    exportExcel() {
      // table 关联导出的DOM节点
      var fixed = document.querySelector(".el-table__fixed");
      var wb;
      var excelTitle = "标题";
      if (fixed) {
        wb = XLSX.utils.table_to_book(
          document.querySelector("#table").removeChild(fixed)
        );
        document.querySelector("#table").appendChild(fixed);
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector("#table"));
      }

      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          excelTitle + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    }
  }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档