Java後臺生成Excel前臺下載
阿新 • • 發佈:2018-12-08
Java後臺通過poi生成HSSFWorkbook
對生成HSSFWorkbook 型別處理 轉為檔案流通過response 返回到前臺
HSSFWorkbook hw = null; try{ hw = ex.export(); //execl 工具類,生成HSSFWorkbook; }catch (Exception e){ e.printStackTrace(); } OutputStream fos = null; try { fos = response.getOutputStream(); String userAgent = request.getHeader("USER-AGENT"); String fileName = "居民資訊"; try { if(StringUtils.contains(userAgent, "Mozilla")){ fileName = new String(fileName.getBytes(), "ISO8859-1"); }else { fileName = URLEncoder.encode(fileName, "utf8"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //設定response返回資訊 response.setCharacterEncoding("UTF-8"); response.setContentType("application/vnd.ms-excel;charset=utf-8");// 設定contentType為excel格式 response.setHeader("Content-Disposition", "Attachment;Filename="+ fileName+".xls"); hw.write(fos); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
前端使用form表單提交,不能使用ajax請求;
function downloadFile(actoinURL,map){ var form = $("<form></form>"); $('#toExcelBtn').append(form); form.attr('style','display:none'); form.attr('target',''); form.attr('method','get'); form.attr('action',actoinURL);//下載檔案的請求路徑 var input1 = $('<input>'); input1.attr('type','hidden'); input1.attr('name','name'); input1.attr('value',map.name); form.append(input1); form.submit(); //提交表單 }
隱藏的form 與input,在input中設定引數值;
下載事件呼叫該方法 ;
然後瀏覽器自動下載到預設路徑;