一般我們實現excel導出都是直接重定向或form表單提交,但如果后台發生異常,提示信息就會在新窗口以文本形式展示,很不友好,這里推薦另一種實現方式,使用post請求,並可以傳遞自定義錯誤信息:
前端使用axios,responseType要設置為blob,也就是二進制文件,在控制台打印是這種樣子:

前端代碼:
exportActivitiesAnalyze: function () { let that= this let params = { activitiesId: activitiesId, startTime: startTime, endTime: endTime } axios({ method: 'post', url: '/activityManage/exportExcel', data: params, responseType: 'blob' }).then(resp => { that.downloadFile(resp,that) }).catch(resp => { that.$notify.error(resp.msg || '導出失敗') }) }
下載方法,實現方式為打開一個新鏈接,然后放置download按鈕,並自動點擊:
downloadFile (resp,that) { let data = resp.data // 此處提示自定義提示語,從header中獲取 if(resp.headers['errormsg'] || !data){ that.$notify.error(decodeURI(resp.headers['errormsg'])||'導出失敗') return } let url = window.URL.createObjectURL(new Blob([data])) let link = document.createElement('a') link.style.display = 'none' link.href = url // 文件名在后端設置 link.setAttribute('download', decodeURI(resp.headers['filename'])) document.body.appendChild(link) link.click() },
后台設置文件信息與文件名:
try { HSSFWorkbook hssfWorkbook = new HSSFWorkbook() String errorMsg = null; /** * 封裝excel數據方法體,此處忽略,可自定百度poi * 根據需要自定義錯誤提示信息,最后放入header * errorMsg = "導出異常:活動不存在" */ String fileName = "excel導出數據.xls"; //清空response response.reset(); //設置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); //提示信息 response.setHeader("errorMsg", URLEncoder.encode(errorMsg, "utf-8")); response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8")); response.setContentType("application/vnd.ms-excel;charset=gb2312"); OutputStream os = new BufferedOutputStream(response.getOutputStream()); hssfWorkbook.write(os); hssfWorkbook.close(); os.flush(); os.close(); } catch (Exception e) { log.error("導出分析數據異常:"+e); throw new RuntimeException(e); }
