vue中下载excel文件

12 篇文章 0 订阅

请求用的axios
请求函数封装
req.js

import axios from 'axios'
const api = axios.create({
 	baseURL : _getBaseUrl(),
});
function _getBaseUrl(){
  const env = process.env.NODE_ENV;
  if (env === 'production') {
    return 'http://xxx.xxx.x.xxx:8080'
  }
  return 'http://xxx.xxx.x.xxx:8080'
}
/**
 * 上传文件
 * @param {请求目录文件} url 
 * @param {文件对象} file 
 * @param {成功回调函数} _cb 
 * @param {失败回调函数} _catchcb 
 */
export function uploadFile (url,file,_cb,_catchcb) {
  const fd = new FormData();
  fd.append('file',file)
  return api.post(url,fd,{
    headers : {
      'Content-Type' : 'multipart/form-data',
      'Access-Control-Allow-Origin' : '*'
    }
  }).then(_cb).catch(_catchcb)
}
/**
 * 下载文件
 * @param {请求url} url 
 * @param {成功回调函数} _cb 
 * @param {失败回调函数} _catchcb 
 */
export function downLoadFile (url,_cb,_catchcb) {
  return api.get(url,{responseType: 'blob'},{
    responseType: 'arraybuffer',
    headers : {
      'Content-Type' : 'application/json',
    }
  }).then(_cb).catch(_catchcb)
}

处理服务端返回文件,工具类封装
tools.js

  /**
   * 处理下载的报表
   * @param {file}  文件对象
   * @param {filename}  需要保存的文件对象名称
   * 保存的文件格式为:filename-年月日.xlsx
   */
  export function operateFile (file,filename) {
    let fileName = fname + "-" + new Date().getFullYear() + '' +( new Date().getMonth()+1)  + '' +new Date() .getDate()+".xlsx";
    let blobObject = new Blob([file], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); 
    //是IE浏览器
    if(!!window.ActiveXObject || "ActiveXObject" in window){
      window.navigator.msSaveOrOpenBlob(blobObject,fileName);
    }else{//火狐谷歌都兼容
    //模板中要有一个预定义好的a标签
      let link = document.getElementById('a_id')
      link.href = URL.createObjectURL(blobObject);
      link.download = fileName
      link.click();
    }
  }
    export default{
    	operateFile: operateFile,
 	 }

组件中调用

<template>
  <div class="inputWrapper">
      <a id="a_id"></a>
      <button class="confirmBtn" @click="dl_confirm">确&nbsp;定</button>     
  </div>
</template>
<script>
  data() {
    return {
    };
  },
 methods: {
 dlConfirm:function(dlData){//下载报表弹框的确定按钮
      console.log(dlData)
      this.downLoadShow = false
      let that = this
      let data = {
        "aaa":ccc,
        "bbb":ddd
      }
      let url = "/terminal/export?"+qs.stringify(data)
      downLoadFile(url,function(res){
        console.log(res)
        if (res.data) {
          tools.operateFile(res.data,"xxx")
        } else {
            console.log("失败")
        }
      },function(err){
        console.log(err)
        that.showToast(err)
      })
    },
 }
 </script>
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值