vue 调用后端接口 导出 Excel表 .pdf , .xls

新建一个封装方法的 exportUtils.js 文件
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.axios = axios;
// 导出
export default {
exportMethod: function(data) {
    axios({
        method: data.method,
        url: data.url,
        data: data.data,
        responseType: 'blob',
        headers: {
            'Content-Type': 'application/json'
        }
    }).then((res) => {
        const link = document.createElement('a')
        let blob = new Blob([res.data], {
            type: 'application/vnd.ms-excel' 
            // type: "application/pdf;charset=utf-8",  //.pdf
        })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob) 
        link.download = data.fileName + '.xls' //下载的文件名  注意:加.xls是兼容火狐浏览器
        document.body.appendChild(link)
        link.click() //会触发a标签的href
       // document.body.removeChild(link)
        link.remove(); // 一次性的,用完就删除a标签
    }).catch(error => {
        console.log(error)
    })
}
}
引用 js 文件:
// 全局引用在  man.js
import exportUtils from "./utils/exportUtils"
Vue.prototype.exportUtils = exportUtils ;
//局部引入,谁用谁引
import exportUtils from "../../utils/exportUtils.js"

调用方法:

1、全局引用
// 导出
    exportOut () {
      let params = { list: this.formInline };
      let myObj = {
        method: 'post',
        url: "/dutyTask/dutyTaskExcel",  //接口地址
        fileName: '值守任务',
        data: params,
      }
      //调用封装方法
      this.exportUtils.exportMethod(myObj);
    },
2、局部引用
    //局部引入,谁用谁引
     import exportUtils from "../../utils/exportUtils.js"

   // 导出
    exportOut () { 
      let params = { list: this.formInline };
      let myObj = {
        method: 'post',
        url: "/dutyTask/dutyTaskExcel",  //接口地址
        fileName: '值守任务',
        data: params,
      }
      //调用封装方法
      exportUtils.exportMethod(myObj);
    },
pdf., xlsx (不封装,直接用)
  async downloadFile(row) {
      let url =https://blog.csdn.net/"; // 后端接口
      let params = { id: row.id };  //  传值 参数
      try {
        let res = await this.$axios.post(url, params, { responseType: "blob" });
        let link = document.createElement("a");
        link.style.display = "none";
        let blob = new Blob([res], {
          type: "application/pdf;charset=utf-8",
          // type: 'application/vnd.ms-excel'   // Excel .xls
        });
        link.href = URL.createObjectURL(blob);
        link.download = `${row.prjName}备案表.pdf`;
        // 获取文件名
        document.body.appendChild(link);
        link.click(); //会触发a标签的href
        link.remove(); // 一次性的,用完就删除a标签
      } catch (error) {}
    },
  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值