在B端项目中,会遇到很多导出Excel的需求,这应该怎么实现呢?根据以下步骤就能快速实现!
在请求拦截器设置contentType
// 文件下载
if (response.status === 200 && response.headers['content-type'] === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
return response;
}
创建请求,指定返回响应类型blob
export const exportEvaluateForm = (params) => ajax.post('/api/v1/xxx/exprotEvaluationForm', params,{
responseType: 'blob'
}); // 导出表
获取blob类型的数据
let res = await exportEvaluateForm({ ids });
const type = res.headers['content-type'];
const blob = new Blob([res.data], {type: `${type};charset=utf-8`});
创建一个a标签
let downloadElement = document.createElement('a');
创建下载链接
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
设置下载文件名
downloadElement.download = '评估表.xlsx';
document.body.appendChild(downloadElement);
模拟点击下载
downloadElement.click();
下载完成移除元素
document.body.removeChild(downloadElement);
释放掉blob对象链接
window.URL.revokeObjectURL(href);
完整代码
// 批量导出评估表
const handleExportEvaluate = async () => {
const ids = [];
selectRows.map((r) => ids.push(r.id));
let res = await exportEvaluateForm({ ids });
const type = res.headers['content-type'];
const blob = new Blob([res.data], {type: `${type};charset=utf-8`});
let downloadElement = document.createElement('a');
// 创建下载的链接
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
// 下载后文件名
downloadElement.download = '评估表.xlsx';
document.body.appendChild(downloadElement);
// 点击下载
downloadElement.click();
// 下载完成移除元素
document.body.removeChild(downloadElement);
// 释放掉blob对象
window.URL.revokeObjectURL(href);
};
公众号
欢迎大家关注我的公众号: 石马上coding,一起成长