最近做的需求中有个导出excel,所以就发一下吧,代码可直接copy,话不多说上代码!
1. 封装fetch
首先创建一个fetchdata.js文件,简单封装一下fetch。
export function PostDataBlob(query) {
return fetch({
method: 'post',
responseType: 'tch',
data: query,
});
}
2. 导出Excel
我的项目是vue,首先在需要下载的页面引入,然后复制 downloadItem 函数代码即可。
import { PostData, PostDataBlob } from "@/api/fetchdata";
// 下载
async downloadItem(row) {
this.loading = true;
let params = {
microservices: "lmall/admins/quota/vision/export",
id: row.id,
device_source: "web",
}
const data = await PostDataBlob(params);
const link = document.createElement('a');
link.style.display = 'none';
link.href = window.URL.createObjectURL(
new Blob([data.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
);
link.setAttribute('download', `${row.name}${this.format(new Date(), 'yyyyMMdd')}.xlsx`);
document.body.appendChild(link);
link.click();
this.loading = false;
},