项目中导出excel文件很常见,分为get
和post
方式,get相对简单些,在url后面拼接需要的参数即可
get请求方式拼接参数长度上限为2083
,超过这个长度导出excel失败
post方式请求返回的是流文件,需要使用blob对象指定要读取的数据,在此记录下
fetch(url, {
method: 'POST',
body: JSON.stringify({}), // 这里放请求数据
headers: {
'Content-Type': 'application/json',
},
}).then((res) =>{
return res.blob();
}).then(response=>{
const blob = new Blob([response], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); // 导出.xlsx结尾的文件
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = '项目销售班型业绩表'+".xlsx";
a.click();
// 释放URL对象
URL.revokeObjectURL(a.href);
})
async
&await
用法
(async function () {
try {
const res = await fetch(url, {
method: 'POST',
body: JSON.stringify({}), // 这里放请求数据
headers: {
'Content-Type': 'application/json',
}
})
const data = await res.blob()
const blob = new Blob([data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }); // 导出.xlsx结尾的文件
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = '项目销售班型业绩表' + ".xlsx";
a.click();
// 释放URL对象
URL.revokeObjectURL(a.href);
} catch (error) { }
})()