一哆姻、導(dǎo)出word
文件名亂碼焦影,使用 JavaScript 對(duì)其進(jìn)行編碼
解決方案:使用 escape 函數(shù)對(duì)其編碼车遂,之后再根據(jù)需求使用 decodeURI 或者 decodeURIComponent 對(duì)其解碼
也是找了好久的解決亂碼的方法,參考自https://blog.csdn.net/weixin_34290000/article/details/91478275
例子
image.png
解碼
image.png
代碼(頁(yè)面直接調(diào)用斯辰,文章末尾加入公用方法)
this.$axios.get(ExportOrganScale,{params:db}, {responseType: `blob` })
.then(res => {
console.log(res)
// word文檔為msword,pdf文檔為pdf舶担,msexcel 為excel(目前get請(qǐng)求只測(cè)試了word下載)
let blob = new Blob([res.data], {type: `application/msword`});
let objectUrl = URL.createObjectURL(blob);
let link = document.createElement("a");
const fileName = res.headers["content-disposition"].match(/filename=(\S*).doc/)[1];
let formatString = escape(fileName)
let fname=decodeURI(formatString)+'.doc'
link.href = objectUrl;
link.setAttribute("download", fname);
document.body.appendChild(link);
link.click();
});
二、導(dǎo)出Excel(此處寫(xiě)了公共方法)
1彬呻、在components中建立文件common.js衣陶,用于存放導(dǎo)出Excel的公共方法derivesXLS
備注:communalApi是分類(名字可隨意修改),用于包含所有的公用方法
2闸氮、在main.js中引入公共js
import common from "./components/common"
Vue.prototype.common = common
3剪况、編寫(xiě)導(dǎo)出公用方法:options接收傳遞參數(shù)(參數(shù)及接口)
import axios from 'axios'
export default {
communalApi:{
derivesXLS(options) { //導(dǎo)出 xls
axios.post(options.url, options.db, {
responseType: "arraybuffer"
})
.then(
res => {
if(res.headers["content-disposition"]==undefined){ //沒(méi)有文件
var enc = new TextDecoder('utf-8')
var txt = JSON.parse(enc.decode(new Uint8Array(res.data)))
if(txt.code==0){
this.$message.error(txt.msg);
return;
}
}
let blob = new Blob([res.data], {
type: "application/vnd.ms-excel"
});
const fileName = res.headers[
"content-disposition"
].match(/filename=(\S*).xls/)[1];
const elink = document.createElement("a");
elink.download = JSON.parse(fileName) + ".xls";
elink.href = window.URL.createObjectURL(blob);
elink.click();
window.URL.revokeObjectURL(elink.href);
},
err => {}
);
},
}
}
4、頁(yè)面使用
var db={}//請(qǐng)求參數(shù)
this.common.communalApi.derivesXLS({
url: '接口名稱',
db: db
});
三蒲跨、導(dǎo)出Word公用方法
方法
derivesDoc(options) {//導(dǎo)出word
axios.get(options.url, {params:options.db}, {
responseType: "arraybuffer"
})
.then(
res => {
// word文檔為msword,pdf文檔為pdf译断,msexcel 為excel(目前get請(qǐng)求只測(cè)試了word下載)
let blob = new Blob([res.data], {type: `application/msword`});
let objectUrl = URL.createObjectURL(blob);
let link = document.createElement("a");
const fileName = res.headers["content-disposition"].match(/filename=(\S*).doc/)[1];
let formatString = escape(fileName)
let fname=decodeURI(formatString)+'.doc'
link.href = objectUrl;
link.setAttribute("download", fname);
document.body.appendChild(link);
link.click();
},
err => {}
);
},
頁(yè)面使用同導(dǎo)出Excel頁(yè)面公用方法調(diào)用一致
4、結(jié)語(yǔ):今天是努力填坑的一天或悲,fignting8渥鳌!隆箩!
image.png
image.png