之前做的项目都是在不调用后台接口的情况下,将json数据导出到excel表格,纯前端去实现导出Excel
最近做的项目,需要向后台传递不同的参数值,后台查询出符合条件的数据,以文档流的格式返回前端,前端再导出为Excel。
调用后端接口,返回的是如下的文件流
此时前端需要把查询到的数据导出为excel格式
//导出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 = "报表.xls";
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
}
}).catch(err => {
console.warn(err);
});
},
注意:在请求接口的时候一定要设置-->responseType: 'blob'
具体可参考MDN文档:https://developer.mozilla.org...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。