實現導出excel的思路是:前端通過ajax的post請求,到后台處理數據,然后把流文件響應到客戶端,供客戶端下載
文件下載方法如下:
public static boolean downloadLocal(HttpServletRequest request,String filePath, String fileName, HttpServletResponse response) throws Exception { // 讀到流中 InputStream inStream = new FileInputStream(filePath);// 文件的存放路徑 // 設置輸出的格式 response.reset();//清除首部的空白行 // 文件編碼 處理文件名中的 '+'、' ' 特殊字符 String encoderName = null; String userAgent = request.getHeader("USER-AGENT"); if(userAgent != null && userAgent.toLowerCase().indexOf("firefox") > 0){ encoderName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?="; } else { encoderName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20").replace("%2B", "+"); } response.setHeader("Content-Disposition", "attachment;filename=\"" + encoderName + "\""); response.setContentType("application/octet-stream; charset=utf-8"); response.setHeader("Accept-Ranges", "bytes"); OutputStream ot = response.getOutputStream(); // 循環取出流中的數據 byte[] b = new byte[1024]; int len; try { while ((len = inStream.read(b)) > 0) { ot.write(b, 0, len); } } catch (Exception e) { return false; }finally{ if(ot!=null){ ot.close(); } if(inStream!=null){ inStream.close(); } } return true; }
但是一直沒有彈出保存提示,查資料后知道:ajax異步請求,dataType格式只支持有xml,html,script,json,jsonp,text,不支持二進制流文件類型
解決方法:
前端改成使用form表單提交方式即可
修改前端代碼如下:
<body> ... <a class="mini-button mini-button-danger" onclick="exportCareerUnit()" >導出</a> ... ... <form id="careerForm" action="${path}/mvc/career/exportCareerUnitMsg" style="display: none" method="post" > <input id="careerSubForm" name="careerSubForm" /> </form> </body> <script> function exportCareerUnit(){ var o = { sys:sysParam }; $("#careerSubForm").val(""); var json = JSON.stringify(o); $("#careerSubForm").val(json); $("#careerForm").submit(); //表單提交 } </script>
解決了問題!
后面看到另一篇文章:https://www.cnblogs.com/dingjiaoyang/p/5831049.html
“如果要將查詢結果導出到Excel,只需將頁面的Context-Type修改一下就可以了:header( "Content-Type: application/vnd.ms-excel">
如果希望能夠提供那個打開/保存的對話框,設置Content-Disposition參數”
等忙過這陣,去試試~