vue將表格匯出為excel

龍恩0707發表於2018-03-18

vue將表格匯出為excel

一:在專案中需要安裝2個依賴項,如下命令:

npm install --save file-saver xlsx

二:在vue檔案中如下使用即可:

<template>
  <div class="hello">
    <h1>vue</h1>
    <h2>{{msg}}</h2>
    <p><button type="button" id="export-table" @click="exportFunc">下載excel檔案</button></p>
    <div id="out-table">
      <table>
        <thead>
          <tr>
            <td>ID</td>
            <td>姓名</td>
            <td>年齡</td>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>111111</td>
            <td>我是前端開發</td>
            <td>今年29歲</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver';
import XLSX from 'xlsx';
console.log(FileSaver);
export default {
  name: 'helloworld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    };
  },
  methods: {
    exportFunc: function(e) {
      // 從表生成工作簿物件
      var wb = XLSX.utils.table_to_book(document.getElementById('out-table'));
      // 得到二進位制字串作為輸出
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        type: 'binary'
      });
      FileSaver.saveAs(new Blob([this.s2ab(wbout)], {
        type: 'application/octet-stream'
      }), 'a.xlsx');
    },
    s2ab: function(s) {
      var cuf;
      var i;
      if (typeof ArrayBuffer !== 'undefined') {
        cuf = new ArrayBuffer(s.length);
        var view = new Uint8Array(cuf);
        for (i = 0; i !== s.length; i++) {
          view[i] = s.charCodeAt(i) & 0xFF;
        }
        return cuf;
      } else {
        cuf = new Array(s.length);
        for (i = 0; i !== s.length; ++i) {
          cuf[i] = s.charCodeAt(i) & oxFF;
        }
        return cuf;
      }
    }
  },
  components: {
    FileSaver,
    XLSX
  }
};
</script>

git上原始碼

注意:table裡面中的表頭thead中不能使用th標籤,否則的話,表頭匯入不出去到excel檔案中,只能使用tr,td這樣的。

相關文章