vue+elementUI表格匯出excel

菜鳥小佳發表於2018-11-16

參考小聖賢君

最終效果

點選導表

跳出匯出檔案

實現過程

1.先安裝依賴

npm install --save xlsx file-saver

2.在需要的元件內引入

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

3.使用---必須保證表格格式對應,不然報錯

 

我用了佈局來寫的表格,然後就會報這個錯

好吧,來看看正確的寫法

<template>
    <div>
        <!-- 匯出按鈕 -->
        <div class="toexcel">
            <el-button  @click="exportExcel" type="primary" class="button" style="width:70px;position:absolute;top:0;right:30px">匯出</el-button>
        </div>
        <el-table
            class="table"
            :data="tableData"
            border
            style="width: 100%">
            <el-table-column
            prop="date"
            label="日期"
            width="180">
            </el-table-column>
            <el-table-column
            prop="name"
            label="姓名"
            width="180">
            </el-table-column>
            <el-table-column
            prop="address"
            label="地址">
            </el-table-column>
        </el-table>
    </div>
</template>

js

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  data() {
    return {
        tableData: [{
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀區金沙江路 1518 弄'
        }, {
          date: '2016-05-04',
          name: '王小虎',
          address: '上海市普陀區金沙江路 1517 弄'
        }, {
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀區金沙江路 1519 弄'
        }, {
          date: '2016-05-03',
          name: '王小虎',
          address: '上海市普陀區金沙江路 1516 弄'
        }]
    };
  },
  methods: {
    // 匯出表格所用
    exportExcel() {
      // 設定當前日期
      let time = new Date();
      let year = time.getFullYear();
      let month = time.getMonth() + 1;
      let day = time.getDate();
      let name = year + "" + month + "" + day;
      // console.log(name)
      /* generate workbook object from table */
      //  .table要匯出的是哪一個表格
      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 {
        //  name+'.xlsx'表示匯出的excel表格名字
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          name + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    }
  }
};
</script>

css

<style scoped>
/* 匯出按鈕 */
.toexcel {
  cursor: pointer;
  cursor: hand;
  width: 70px;
  height: 34px;
}
</style>

可以直接用,菜鳥歡迎大神指點

相關文章