vue 用axios實現調用接口下載excel


了解的方式有兩種:

1. 用a標簽,href設置為后端提供的excel接口

<a href="excel接口">導出</a>

簡單方便,缺點就是當有token校驗時,不適合

2. 用axios

把token放在請求的header里邊

import axios from 'axios'
import { getToken } from 'js-cookie';

methods: {
    exportExcel () {
        let url = 'http...',
            token = getToken();
        axios.get(url, {
            headers:{
                "Admin_token":token
            },
            responseType: 'blob', //二進制流
        }).then(function (res) {
            if(!res) return
            let blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'})
            let url = window.URL.createObjectURL(blob);
            let aLink = document.createElement("a");
            aLink.style.display = "none";
            aLink.href = url;
            aLink.setAttribute("download", "excel.xls");
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink); 
            window.URL.revokeObjectURL(url); 
        }).catch(function (error) {
            console.log(error)
        });
    }
}

 

注:如果上面的方法還是亂碼,請嘗試一下方法:

 1.如果裝了mockjs,把mockjs去掉

 2.使用原生的js請求

 

 

參考:https://blog.csdn.net/xuesheng1610748/article/details/83865679


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM