1. 程式人生 > >前端資料傳到後臺動態生成Excel檔案並提供檔案下載

前端資料傳到後臺動態生成Excel檔案並提供檔案下載

需求描述:
需要將前端的某些資料生成Excel檔案,並提供下載功能。
解決方案:
前端通過ajax的方式將資料資訊傳到後臺,後臺使用POI元件動態生成Excel檔案流,並寫入資料資訊,返回前端供前端下載。
程式碼示例:

// 前端程式碼
$.ajax({
                    url: "/ExportExcelServer/SubmitExcelData",
                    type: "post",
                    dataType: "json",
                    data:paramData,
                    success: function
(data) {
if (data&&data.code=="1") { window.location.href = "/ExportExcelServer/DownloadExcel"; } else { $.dialog.alert("下載失敗!"); } }, error: function
(err) {
$.dialog.alert("下載失敗"); } });
// 後臺介面程式碼
 @RequestMapping(value="/SubmitExcelData",method = RequestMethod.POST)
    public String submitExcelData(HttpServletRequest request, HttpServletResponse response,String paramJson)throws
IOException { // 設定響應和請求編碼utf-8 request.setCharacterEncoding("UTF-8"); JSONObject jsonResult=new JSONObject(); // 返回介面端的json物件 if (paramJson == null) { jsonResult.put("code","0"); jsonResult.put("msg","失敗,傳入引數為空"); return jsonResult.toString(); } // 將引數資訊存入session中 HttpSession session = request.getSession(); try { session.setAttribute("param", paramJson); jsonResult.put("code","1"); jsonResult.put("msg","成功!"); } catch (Exception e) { jsonResult.put("code","0"); jsonResult.put("msg","失敗,失敗原因:"+e.getMessage()); return jsonResult.toString(); } return jsonResult.toString(); } @RequestMapping(value="/DownloadExcel") public void downloadExcel(HttpServletRequest request, HttpServletResponse response)throws IOException { // 設定響應和請求編碼utf-8 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); String strData = (String) session.getAttribute("param"); if (strData == null||strData.equals("")) { response.getWriter().write("失敗,失敗原因:引數為空!"); return; } // 建立Excel // 省略....... // region 解析base64位的編碼為圖片 BASE64Decoder decoder = new BASE64Decoder(); // 圖片base編碼解密 byte[] byteImgs = decoder.decodeBuffer(strImgBase64); // 處理資料 for (int j = 0; j < byteImgs.length; ++j) { if (byteImgs[j] < 0) { byteImgs[j] += 256; } } // endregion //region 設定返回標頭檔案 String strFileName="data.xls";// 預設Excel名稱 response.setContentType("application/octet-stream; charset=utf-8"); if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0){ response.setHeader("Content-Disposition", "attachment; filename=" + new String(strFileName.getBytes("UTF-8"), "ISO8859-1"));// firefox瀏覽器 } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){ response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(strFileName, "UTF-8"));// IE瀏覽器 }else{ response.setHeader("Content-disposition", "attachment;filename="+strFileName); } // endregion response.flushBuffer(); workbook.write(response.getOutputStream()); } } catch (Exception e) { response.getWriter().write("失敗,失敗原因:"+e.getMessage()); } }