最近在写项目的时候遇到一个需求,要求将后台管理系统的文件以Excel的形式导出。
实现起来也不难,首先封装一个方法:
js代码:
function exportExcel (data, name) {
let blob = new Blob([data], { type: "application/vnd.ms-excel" }); // 设置文件类型excel
let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
// 创建url之后可以模拟对此文件对象的一系列操作,例如:预览、下载
let a = document.createElement("a");
a.href = url;
a.download = name + ".xlsx";
a.click();
// 释放这个临时的对象url
window.URL.revokeObjectURL(url);
}
export default {
exportExcel
}
使用方法如下:
let res = await this.request.postResponseType(
`${this.api.gameUserSignExport.request.url}`,
{
gameId: data.gameId,
gameItemId: data.id,
},
{ responseType: "blob" }
);
if (res) {
let name = "团体报名列表 " + this.util.currentDate();
this.util.exportExcel(res, name);
}