js导出文件

在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,一起成长
石马上coding

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值