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(); }