excel文件下载处理两种方法

本文介绍了如何在Vue.js项目中使用async/await和blob对象实现数据的异步导出,通过`commonExportData`函数,用户可以将axios请求返回的blob数据转换为可下载的Excel文件,包括了两种方法:直接引用外部js文件和独立处理URL。

excel.js文件 

export async function commonExportData(res) {
	//转换成二进制对象
  const type ="application/x-download;charset=UTF-8";
	const blob = new Blob([res],{type:type});
	const downloadElement = document.createElement('a');

	//二进制对象转换成url地址
	const href =window.URL.createObjectURL(blob);
	downloadElement.href = href;
  //获取headers中的filename文件名
	downloadElement.download = 'excel.xlsx';
	//下载
	document.body.appendChild(downloadElement);
	downloadElement.click();
	//下载完成移除元素
	document.body.removeChild(downloadElement);
	//释放掉blob对象
	window.URL.revokeObjectURL(href);
}
方法一引用外部js文件
import { commonExportData } from '@/utils/excel';

//excel模板导出
        async exportPage(){
            let paramPageId = this.pageData.pageId;
方法一://引入excel.js文件的方法
       // axios({
			// 	method: 'get',
			// 	url: this.envUrl +'fsp-lowcode-client/page/exportPage?pageId=' + paramPageId,
			// 	responseType: 'blob', // 设置返回数据的类型为blob
			// })
            // .then((res) => {
            //     console.log(res.code)
            //     commonExportData(res.data);
            //     }).catch((e) => console.log(e));
方法二:
            let url = this.envUrl +'fsp-lowcode-client/page/exportPage?pageId=' + paramPageId;
            let res = await this.exportPageModel(url);
			if (res.data) {
				const content = res.data;
				const blob = new Blob([content]);
				const fileName = `【${this.projectInfo.projectName}】-【${this.pageData.pageName}】数据导入模板.xls`;
				const elink = document.createElement('a');
				elink.download = fileName;
				elink.style.display = 'none';
				elink.href = URL.createObjectURL(blob);
				document.body.appendChild(elink);
				elink.click();
				URL.revokeObjectURL(elink.href); // 释放URL 对象
				document.body.removeChild(elink);
			} else {
				this.$message('文件导出失败,请重试');
			}
        },
        exportPageModel(url){
            return axios({
				method: 'get',
				url: url,
				responseType: 'blob',
			});
        },

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值