vue導(dǎo)出excel文件流中文亂碼問題及解決
導(dǎo)出excel文件流中文亂碼
解決此方法很多網(wǎng)上的差不多都可以。一下提供簡單的方法
loads(){ let data={ userWord:this.dataList.userWord, examId:this.$route.query.id, exportType:this.active, } api.exportUserResult(data).then((res) => { const blob = new Blob([res.data]); const fileName = '考試成績.xls'; const linkNode = document.createElement('a'); linkNode.download = fileName; //a標(biāo)簽的download屬性規(guī)定下載文件的名稱 linkNode.style.display = 'none'; linkNode.href = URL.createObjectURL(blob); //生成一個Blob URL document.body.appendChild(linkNode); linkNode.click(); //模擬在按鈕上的一次鼠標(biāo)單擊 URL.revokeObjectURL(linkNode.href); // 釋放URL 對象 document.body.removeChild(linkNode); }); },
注意:
填寫
另住攔截器,因為判斷result,沒在正確里返回,所以我直接返回
導(dǎo)出excel亂碼(錕斤拷唷?錕?;錕斤拷)
我這個是 post請求亂碼了 ,如果是get,就直接window.open(url,'_blank')就可以了
1.“錕斤拷唷?錕?;錕斤拷”這種亂碼信息導(dǎo)致的原因是:整個數(shù)據(jù)流的字符集 GBK=>UTF-8=>GBK導(dǎo)致的。
2. 前端代碼:
axios({ method: "post", url: url, data: params, headers: { // ... 接口需要的請求頭 }, responseType: "blob" }).then(response => { const blob = new Blob([res.data],{type: 'application/vnd.ms-excel'}); const fileName = res.headers["content-disposition"].split("=")[1]; //接口響應(yīng)頭定義的文件名 downloadFile(blob, fileName); });
//import { Message } from "element-ui"; /** * 文件下載, 對于下載鏈接可直接用 window.open(url, "_blank"); * @param {*} data 二進制數(shù)據(jù)或base64編碼 Blob、String * @param {*} fileName 下載的文件命名,可帶擴展名,跨域下無效 */ export function downloadFile(data, fileName) { let url = ""; let isBlob = false; const errMsg = "下載出錯,文件數(shù)據(jù)無法識別!"; if (data instanceof Blob) { isBlob = true; url = window.URL.createObjectURL(data); } else if (typeof data == "string") { // base64編碼 url = data; } else { Message.error(errMsg); return; } if ("download" in document.createElement("a")) { // 非IE下載 const tmpLink = document.createElement("a"); tmpLink.download = fileName || ""; tmpLink.style.display = "none"; tmpLink.href = url; document.body.appendChild(tmpLink); tmpLink.click(); window.URL.revokeObjectURL(tmpLink.href); // 釋放URL 對象 document.body.removeChild(tmpLink); } else { // IE10+下載 if (isBlob) { window.navigator.msSaveBlob(data, fileName); } else { //Message.error(errMsg); console.log(errMsg); return; } } }
3. 感覺完美 但是結(jié)果下載下來的如一開始截圖的亂碼,其實代碼沒有問題,問題在于前端項目啟用了mock.js,把所有 import 或 require @/mock 的地方注釋調(diào)就可以了
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue.js如何利用v-for循環(huán)生成動態(tài)標(biāo)簽
這篇文章主要給大家介紹了關(guān)于Vue.js如何利用v-for循環(huán)生成動態(tài)標(biāo)簽的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-01-01詳解Vue的數(shù)據(jù)及事件綁定和filter過濾器
這篇文章主要為大家介紹了Vue的數(shù)據(jù)及事件綁定和filter過濾器,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-01-01