vue使用axios實(shí)現(xiàn)excel文件下載的功能
前端VUE頁面上的導(dǎo)出或者下載功能,一般是調(diào)用后端的一個接口,由接口生成excel,word這些文件的流信息,返回給vue,然后由vue去構(gòu)建下載的動作,這邊整理了一下,封裝了一下,方便以后復(fù)用。
封裝一個download文件
使用年月日時分秒毫秒做為文件的名稱,下載為excel文件
/**
* 下載文件
*/
export const downloadFile = (url,ext, params) => {
let accessToken = getStore('accessToken');
return axios({
method: 'get',
url: `${base}${url}`,
params: params,
headers: {
'accessToken': accessToken
},
responseType: 'blob', //二進(jìn)制流
}).then(res => {
// 處理返回的文件流
const content = res;
const blob = new Blob([content], { type: 'application/vnd.ms-excel;charset=utf-8' });
var date =
new Date().getFullYear() +
"" +
(new Date().getMonth() + 1) +
"" +
new Date().getDate() +
"" +
new Date().getHours() +
"" +
new Date().getMinutes() +
"" +
new Date().getSeconds() +
"" +
new Date().getMilliseconds();
const fileName = date + "." + ext;
if ("download" in document.createElement("a")) {
// 非IE下載
const elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 釋放URL 對象
document.body.removeChild(elink);
} else {
// IE10+下載
navigator.msSaveBlob(blob, fileName);
}
});
};
為具體功能封裝一個組件,方便在前臺調(diào)用
// 評價導(dǎo)出
export const getRecordExport= (params) => {
return downloadFile('/record/export',"xlsx", params)
}
vue頁面上調(diào)用它,實(shí)現(xiàn)導(dǎo)出
<script>
import {
getReportExport
} from "@/api/index";
import util from "@/libs/util.js";
export default {
name: "task-manage",
data() {},
methods: {
exportExcel() {
getReportExport(this.searchForm).then(res=>{});
}
}
}
截圖

到此這篇關(guān)于vue使用axios實(shí)現(xiàn)excel文件下載的功能的文章就介紹到這了,更多相關(guān)vue實(shí)現(xiàn)excel文件下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue+Element-UI中el-table動態(tài)合并單元格:span-method方法代碼詳解
el-table是element-ui提供的表格組件,可以用于展示和操作數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于Vue+Element-UI中el-table動態(tài)合并單元格:span-method方法的相關(guān)資料,需要的朋友可以參考下2023-09-09
Vue2.x中的父組件傳遞數(shù)據(jù)至子組件的方法
這篇文章主要介紹了Vue2.x中的父組件數(shù)據(jù)傳遞至子組件的方法,需要的朋友可以參考下2017-05-05
vue使用docx-preview實(shí)現(xiàn)docx文件在線預(yù)覽功能全過程
文件在線預(yù)覽是目前移動化辦公的一種新趨勢,下面這篇文章主要給大家介紹了關(guān)于vue?docx-preview實(shí)現(xiàn)docx文件在線預(yù)覽功能的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04
Vue數(shù)組響應(yīng)式操作及高階函數(shù)使用代碼詳解
這篇文章主要介紹了Vue數(shù)組響應(yīng)式操作及高階函數(shù)使用代碼詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08

