vue导出table内容至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>

注意:table里面中的表头thead中不能使用th标签,否则的话,表头导入不出去到excel文件中,只能使用tr,td这样的。

 

------------------------------------------------------------------------------------------------------

转自:https://www.cnblogs.com/tugenhua0707/p/8597050.html

转载于:https://www.cnblogs.com/liuboyuan/p/11340030.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值