Vue 导出 excel 表格(调用后端接口转化为二进制流导出)

一、直接上代码(部分代码)

	<el-button
	  type="success"
	  icon="el-icon-download"
	  @click="batchExport"
	>批量导出</el-button>

	// 批量导出
    batchExport() {
      const params = {
        orderType: this.queryInfo.type,
        userName: this.queryInfo.user,
        orderNum: this.queryInfo.number
      }
      if (this.queryInfo.date) {
        params.startTime = this.queryInfo.date[0]
        params.endTime = this.queryInfo.date[1]
      } else {
        // 默认批量导出今天
        params.startTime = `${this.getCurrentDate()} 00:00:00`
        params.endTime = `${this.getCurrentDate()} 23:59:59`
      }
      getFlow(params).then(res => {
        this.downloadFile(res, '订单列表.xls')
      })
    },
    // 下载
    downloadFile(data, filename) {
      // 接收的是blob,若接收的是文件流,需要转化一下
      if (typeof window.chrome !== 'undefined') {
        // Chrome version
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(data)
        link.download = filename
        link.click()
      } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
        // IE version
        const blob = new Blob([data], { type: 'application/force-download' })
        window.navigator.msSaveBlob(blob, filename)
      } else {
        // Firefox version
        const file = new File([data], filename, { type: 'application/force-download' })
        window.open(URL.createObjectURL(file))
      }
    },
    // 获取当前时间
    getCurrentDate() {
      const dt = new Date()
      const year = dt.getFullYear()
      const month = String(dt.getMonth() + 1).padStart(2, '0')
      const date = String(dt.getDate()).padStart(2, '0')
      return `${year}-${month}-${date}`
    }


	// api.js 文件(注意:我这里将请求封装了,具体代码就不一一展示了)
    // 获取二进制流(批量导出时用)
	const getFlow = params => {
  	  return axios.get2(baseUrl + '/TrainingCenter/order/export', { params })
	}
	// get 方法2,获取二进制流
  	get2(url, data) {
      const options = Object.assign(
        {
          method: 'get',
          url,
          responseType: 'blob' // 将接口返回数据类型设置为 blob 类型
        },
        data
      )
      return this.request(options)
  	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值