1.在项目中安装file saver和xlsx库,如下:

npm install --save xlsx file-saver

2.在有下载功能的组件上,加入引用

import { saveAs } from "file-saver";
import XLSX from "xlsx";

3.使用table_to_book方式导出。该方式需要在导出的数据所在的table有唯一标识符,如id

<template>
  <div>
    <el-button type="" @click="downloadData()">下载</el-button>
    <el-table :data="tableData" height="400" id="download"> //id作为唯一标识,用于下载数据
      <el-table-column
        type="selection"
        width="50"
        v-if="showColumn == true"
        :key="Math.random()"
      ></el-table-column>
      <el-table-column
        label="序号"
        prop="id"
        v-else
        :key="Math.random()"
      ></el-table-column>
      <el-table-column label="英文名" prop="value"></el-table-column>
      <el-table-column label="中文名" prop="label"></el-table-column>
    </el-table>
    <el-button plain style="width:100px" @click="showColumn = true"
      >显示</el-button
    >
    <el-button plain style="width:100px" @click="showColumn = false"
      >隐藏</el-button
    >
  </div>
</template>

4.js下载数据代码如下

<script>
import { saveAs } from "file-saver";
import XLSX from "xlsx";
export default {
  name: "TableColumnShowHideDemo",
  data() {
    return {
      table_interval: null,
      showColumn: false,
      tableData: [
        { id: "1", value: "right", label: "正确" },
        { id: "2", value: "wrong", label: "错误" },
        { id: "3", value: "rightorwrong", label: "正确or错误" },
        { id: "4", value: "right", label: "正确" },
        { id: "5", value: "wrong", label: "错误" },
        { id: "6", value: "rightorwrong", label: "正确or错误" },
        { id: "7", value: "right", label: "正确" },
        { id: "8", value: "wrong", label: "错误" },
        { id: "9", value: "rightorwrong", label: "正确or错误" },
        { id: "10", value: "right", label: "正确" },
        { id: "11", value: "wrong", label: "错误" },
        { id: "12", value: "rightorwrong", label: "正确or错误" },
        { id: "13", value: "right", label: "正确" },
        { id: "14", value: "wrong", label: "错误" },
        { id: "15", value: "rightorwrong", label: "正确or错误" }
      ]
    };
  },
  methods: {
    downloadData: function() {
      this.exportExcel("download", "测试");
    },
    exportExcel: function(id, fileName) {
      var wb = XLSX.utils.table_to_book(document.querySelector("#" + id));
      var wt = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        saveAs(
          new Blob([wt], { type: "application/octet-stream" }),
          fileName + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wt);
      }
    }
  }
};
</script>

5.页面如下图所示:

6.下载Excel数据如下:

 

 

Logo

前往低代码交流专区

更多推荐