React实现导出功能
React实现导出功能
1、React导出excel功能
<Button colors="primary" onClick={_this.export}>
导出
</Button>
export=()=>{
let searchObj = {searchMap:{}};
let {searchMap} = searchObj;//查询条件
let downUrl = `api/export`
exportFile(downUrl,{searchMap})
}
1> 使用Blob对象,从服务器接收到的文件流创建了一个blob对象,并使用该blob创建一个指向类型数组的URL,将该url作为a标签的链接目标,
然后去触发a标签的点击事件从而实现表格下载导出函数代码如下
function exportFile(url, data) {
axios({
method: 'post',
url: url,
data: data,
responseType: 'blob'
}).then((res) => {
const content = res.data;
const blob = new Blob([content]);
const fileName = "导出数据.xls";
const selfURL = window[window.webkitURL ? 'webkitURL' : 'URL'];
let elink = document.createElement('a');
if ('download' in elink) {
elink.download = fileName;
elink.style.display = 'none';
elink.href = selfURL['createObjectURL'](blob);
document.body.appendChild(elink);
// 触发链接
elink.click();
selfURL.revokeObjectURL(elink.href);
document.body.removeChild(elink)
} else {
navigator.msSaveBlob(blob, fileName);
}
})
}
2> 使用form表单,采用GET方法,参数通过input值传给后台,接收后台返回的文件流直接下载,这里注意后台接收不能用注解requestBody,而是用注解requestParam,而且url过长,不友好
exportFile(url, data) {
//data是post请求需要的参数,url是请求url地址
var form = document.createElement("form");
form.style.display = "none";
form.action = url;
form.method = "get";
document.body.appendChild(form);
// 动态创建input并给value赋值
for (var key in data) {
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = params[key];
form.appendChild(input);
}
form.submit();
form.remove();
}
本文来自博客园,作者:玖捌,转载请注明原文链接:https://www.cnblogs.com/fyh0912/p/14314193.html

浙公网安备 33010602011771号