上图是后台返回的数据,此时前端需要把查询到的数据导出为excel格式,这里介绍两种方法:
第一种:
getExcel() {
const url = 'URL地址';
this.$http.post(url, this.filter, {
responseType: 'blob'
}).then(res => {
let blob = new Blob([res.data], {
type: "application/vnd.ms-excel",
});
let objectUrl = URL.createObjectURL(blob);
window.location.href = objectUrl;
}).catch(err => {
console.warn(err);
});
},
注意设置responseType!!!
Blob()
构造函数返回一个新的 Blob
对象。 blob的内容由参数数组中给出的值的串联组成。
语法:var aBlob = new Blob( array, options );
Blob.type:一个字符串,表明该Blob
对象所包含数据的MIME类型。如果类型未知,则该值为空字符串。
具体可参考MDN文档:Blob - Web API 接口 | MDN
此方法的缺陷:下载的excel文档的名字是,创建的blob的url,且无法使创建的url为固定值,在每次调用 createObjectURL()
方法时,都会创建一个新的 URL 对象
第二种:
//导出Excel
getExcel() {
const url = '你的URL';
this.$http.post(url, params, {
responseType: 'blob'
}).then(res => {
let blob = new Blob([res.data], {
type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob);
} else {
let elink = document.createElement('a');
elink.download = "报表.xlsx";
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
}
}).catch(err => {
console.warn(err);
});
},
第二种方法可以自己设置导出excel的名称。利用a链接,最后记得对a 链接进行移除。
你学会了吗?