需求 IE11能正确导出excel表格
var blob = new Blob([res.data], {
type: "application/vnd.ms-excel;charset=UTF-8"
});
var downloadElement = document.createElement("a");
//从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
var contentDisposition = res.headers["content-disposition"];
var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
var result = patt.exec(contentDisposition);
var filename = result[1];
var href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.style.display = "none";
downloadElement.href = href;
downloadElement.download = filename; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
以上代码是导出excel的代码
res是使用axios调用接口之后返回的response接口
此代码在谷歌导出excel是完全没问题,但是在ie11点击导出却没有反应
所以需要做一下兼容性
将公共代码提取出来
var blob = new Blob([res.data], {
type: "application/vnd.ms-excel;charset=UTF-8"
});
var downloadElement = document.createElement("a");
//从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
var contentDisposition = res.headers["content-disposition"];
var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
var result = patt.exec(contentDisposition);
var filename = result[1];
因为ie11revokeObjectURL方法不兼容
所以需要使用msSaveOrOpenBlob这个方法
if ("msSaveOrOpenBlob" in navigator) {
//兼容ie
window.navigator.msSaveOrOpenBlob(blob, filename);
return;
} else {
var href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.style.display = "none";
downloadElement.href = href;
downloadElement.download = filename; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
}
}
word文档同理 只需要修改new Blod的type属性即可
var blob = new Blob([res.data], {
type:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8"
}); //application/vnd.openxmlformats-officedocument.wordprocessingml.document这里表示doc类型
网友评论