1. 程式人生 > >POI匯出Excel檔案,瀏覽器點選可下載

POI匯出Excel檔案,瀏覽器點選可下載

說明:使用SpringMVC+POI

1:服務端程式碼

/**
   * 匯出日誌查詢列表
   */
  @RequestMapping(value = "/log_excel")
  public void exportLogList(HttpServletRequest request, OperationLog vo, @RequestParam(value = "pageNo", required = false) Integer pageNo,HttpServletResponse response) throws CodeException {
      try {
          HSSFWorkbook workbook = new
HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("日誌資訊列表"); HSSFRow headRow = sheet.createRow(0); //這是一些要匯出列的標題 String[] title = new String[] { "ID","操作時間"}; for (int i = 0; i < title.length; i++) { headRow.createCell(i).setCellValue(title[i]); } //要匯出的資料物件集合
List<OperationLog> list = page.getBeans(); if (list != null && list.size() > 0) { for (OperationLog log : list) { HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1); this.setCellStyle(workbook,dataRow.createCell(0
),log.getId()); this.setCellStyle(workbook,dataRow.createCell(1),new SimpleDateFormat("yyyy-MM-dd").format(log.getCreateTime())); } } sheet.autoSizeColumn(1, true); //物件置空 list = null; response.reset(); response.setContentType("application/ms-excel;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("日誌資訊列表.xls", "UTF-8")))); try { workbook.write(response.getOutputStream()); response.getOutputStream().flush(); } catch (Exception e) { sysLog.error("日誌列表Excel匯出出錯", e); throw e; }finally{ if(workbook!=null){ workbook.close(); } if(response.getOutputStream()!=null){ response.getOutputStream().close(); } } } catch (CodeException ce) { sysLog.error("日誌列表Excel匯出出錯", ce); throw ce; } catch (Exception e) { sysLog.error("日誌列表Excel匯出出現系統錯誤", e); throw new CodeException(CodeConstants.SYS_ERROR, new Object[] { "日誌列表Excel匯出出現系統錯誤" }, e); } } public HSSFCell setCellStyle(HSSFWorkbook workbook,HSSFCell cell,String value){ HSSFCellStyle cellStyle = workbook.createCellStyle(); HSSFDataFormat format = workbook.createDataFormat(); cellStyle.setDataFormat(format.getFormat("@")); cell.setCellStyle(cellStyle); cell.setCellValue(value); return cell; }

瀏覽器請求程式碼

//當點選下面元素的時候,請求該對映路徑,然後就會彈出下載框
 $("#QueryExcel").click(function(){
     $("#QueryForm").attr("action","${root}/logManagement/001/log_excel.do");
     $("#QueryForm").submit();
 });