vue实现点击按钮导出Excel

24 篇文章 0 订阅

导出(静态导出)

所用技术

利用 xlsx 和 file-saver 导出Excel
点击对应按钮导出表单数据生成Excel格式

如下所示:
在这里插入图片描述

代码

!<template>
  <div>
     <div class="toexcel">
     <el-button  @click="exportExcel" type="primary" :disabled="disable">导出</el-button>
    </div>
    <!--  -->
    <!-- 表格 -->
    <table class="table">
      <tr>
        <td class="grid-content">代理ID</td>
        <td class="grid-content">代理等级</td>
        <td class="grid-content">账户名称</td>
        <td class="grid-content">代理名字</td>
        <td class="grid-content">代理上限额度</td>
        <td class="grid-content">注册日期(北京)</td>
        <td class="grid-content">状态</td>
        <td class="grid-content">总玩家数量</td>
        <td class="grid-content">上级代理ID</td>
        <td class="grid-content">服务器名称</td>
      </tr>
      <tr v-for="(item,index) in tableData" :key="index">
        <td class="hcontent">{{item.ID}}</td>
        <td class="hcontent">{{item.rank}}</td>
        <td class="hcontent">{{item.account}}</td>
        <td class="hcontent">{{item.name}}</td>
        <td class="hcontent">{{item.max}}</td>
        <td class="hcontent">{{item.time}}</td>
        <td class="jcontent">{{item.status}}</td>
        <td class="hcontent">{{item.num}}</td>
        <td class="hcontent">{{item.lastID}}</td>
        <td class="hcontent">{{item.server}}</td>
      </tr>
    </table>
    <!-- 导出 -->
  </div>
</template>
<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  data() {
    return {
      // 计时器------导表按钮3秒内不能重复点击
      oldtime:3,//秒数
      disable:false,//导表按钮是否禁用
      guide:null,//导表计时器
      //计时器结束-----------------------------
      tableData: [
        {
          ID: "1100",
          rank: "三级代理商",
          account: "a3",
          name: "a3",
          max: "1,000.000",
          time: "2018-10-23 01:19:22",
          status: "正常",
          num: "0",
          lastID: "1034",
          server: "演示服"
        },
        {
          ID: "1102",
          rank: "三级代理商",
          account: "a3",
          name: "a3",
          max: "1,000.000",
          time: "2018-10-23 01:19:22",
          status: "正常",
          num: "0",
          lastID: "1034",
          server: "演示服"
        }
      ]
    }
  },
  methods:{
    // 导表按钮3秒内不能点击,3秒后恢复
     exportButton(){
      this.oldtime=3;
      this.disable=true;
      this.guide =setInterval(()=>{
        this.oldtime--
        if (this.oldtime==0) {
          clearInterval(this.guide)
          this.disable=false;
        }
      },1000)
    },
    exportExcel(){
      // 控制多次点击延迟3秒
       this.exportButton()
      // 设置当前日期
      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;
    },
    // 确保清除计时器
   beforeDestroy(){
    clearInterval(this.guide);
    this.guide=null;
  }
  }
};
</script>

<style lang="scss" scoped>
.hcontent{
  background-color: transparent;
  border: 1px solid #ddd;
  font-size: 16px;
}
</style>

参考

导出(后端接口)

这个导出是导出全部的数据 如果卡条件进行拼接即可

后端提供的是数据流的格式
在这里插入图片描述

如下所示:

<el-button size="mini" type="primary" @click="exportData">导出</el-button>
导出不需要加密直接拿到请求数据接口进行调用请求
// 导出操作
exportData() {
  //首先拿到完整的接口路径(fileData)  
  //this.$appConst.baseUrl这个是共用的接口头
      let fileData = this.$appConst.baseUrl + "/XXXX/XXXs/xxxx/xxxxLog"
      const url = window.URL.createObjectURL(
        new Blob([fileData], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
        })
      )
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', '文件') 
      // 下载文件的名称及文件类型后缀
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) // 下载完成移除元素
      window.URL.revokeObjectURL(url) // 释放掉blob对象
    },
}

批量导出(后端接口)

导出会带勾选状态
selectedRowkeys 自定义的勾选状态
<el-button size="mini" type="primary" @click="exportData">导出</el-button>
export default {
    data() {
        return {
            url: {
                exportXlsUrl: 'yruei/owskdjchvb'
            }
        }
    },
    created() {
    },
    methods: {
        exportData(fileName, type) {
            // selectedRowKeys 勾选状态
            if (this.selectedRowKeys.length <= 0) {
                //弹出提示
                this.$message.warn('至少选择一个记录')
            }
            if (!fileName || typeof fileName !== 'string') {
                fileName = "导出文件"
            }
            let batchNos = []//定义一个空数组
            if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
                this.selectedRowKeys.forEach(item => {
                    batchNos.push(item)//push方法将一个或多个元素插入数组的尾部
                })
            }
            //  判断单勾还是多勾状态
            let parma = {}
            parma = Object.assign({}, this.queryParam)
            parma['batchNos'] = batchNos
            if (type == '1') {
                this.url.exportXlsUrl = this.url.exportXlsUrl //(单个)
            } else {
                this.url.exportXlsUrl = this.url.downloadModules//(多个)
            }
            // 对应接口请求 downFile是引入的接口路径
            downFile(this.url.exportXlsUrl, parma).then((data) => {
                if (!data) {
                    this.$message.warning("文件下载失败")
                    return
                }
                if (typeof window.navigator.msSvaeBlob !== 'undefined') {
                    // 兼容IE10
                    window.navigator.msSaveBlob(new Blob([data]), fileName + '.xlsx')
                } else {
                    let url = window.URL.createObjectURL(new Blob([data]))
                    let link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download', fileName + '.xlsx')
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)// 下载完后移除元素
                    window.URL.revokeObjectURL(url)// 释放掉blob对象
                }
            })
        }
    }
}
</script>

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值