spring mvc 匯出下載Excel
阿新 • • 發佈:2019-01-23
Controller: public void exportPcrList(HttpServletRequest request,HttpServletResponse response,Integer status,String date){ // 宣告一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); List<Map<String,Object>> lists=new ArrayList<Map<String,Object>>(); lists =service.exportNewPcrList(status,date); ExportExcel<Primer> ex = new ExportExcel<Primer>(); String[] headers = {"樣本名稱","引物F","引物R","片段長度","退火溫度","酶","測序引物","日期","溶解型別"}; String[] columNames = {"sampleName","fFrimer","rFrimer","length","temper","enzyme","frimer","handleTime","orderType"}; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { workbook = ex.exportPcr(workbook,0,"新引物工單",headers,columNames,lists,"yyyy-MM-dd"); ByteArrayOutputStream os = new ByteArrayOutputStream(); workbook.write(os); byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(content); // 設定response引數,可以開啟下載頁面 Timestamp tmp = DateUtils.stringToTimestamp(date); String dateString = DateUtils.getDate2All(tmp); String fileName = dateNowStr+"匯出的資料.xls"; response.reset(); response.setHeader("Content-disposition", dateString); response.setContentType("application/vnd.ms-excel;charset=utf-8"); //中文亂碼下載解決方法 fileName = new String(fileName.getBytes("utf-8"),"iso-8859-1"); response.setHeader("Content-disposition", "attachment; filename=" + fileName); ServletOutputStream out = response.getOutputStream(); bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (final Exception e) { e.printStackTrace(); }finally { try { if (bis != null){ bis.close(); } if (bos != null){ bos.close(); } } catch (IOException e) { e.printStackTrace(); } } }