1. 程式人生 > >【springmvc】通過POI下載檔案的實現過程

【springmvc】通過POI下載檔案的實現過程

通過POI下載檔案的實現過程

整體程式碼實現思路

  1. 首先在jsp頁面中,設定一個匯出功能按鈕,在匯出功能函式中,通過window.location.href的方式開啟一個新的頁面;
  2. 後臺的export函式中做兩部分操作
  3. 操作一:將資料庫中的資料讀取出來,寫入到一個HSSFWorkbook檔案中
  4. 操作二:將HSSFWorkbook檔案,新增到response的out流中,返回給前臺新開啟的頁面。從而完成下載功能

前臺程式碼

//匯出按鈕
    function exportClick() {
    	var beginDate = $('#beginDate').datebox('getValue');
        var endDate = $('#endDate').datebox('getValue');
        if(beginDate != null && beginDate != "" && endDate != null && endDate != "") {
        	layer.confirm('是否匯出時間為'+beginDate+'至'+endDate+'的獎懲資訊?', {
                btn: ['確認', '取消'] //按鈕
            }, function () {
            	layer.close(layer.index);
            	window.location.href = "${pageContext.request.contextPath}/staff/policeReward/export.do?beginDate=" + beginDate+"&endDate=" + endDate;
            });
        }else {
        	layer.msg("請選擇匯出時間範圍", {icon: 2});
        }
    }

後臺程式碼

    /**
     * 匯出日誌查詢列表
     * @author 老魏
     * @date 2018-10-09
     * @param pageParams 		分頁引數
     * @return
     */
    @RequestMapping(value = "/export")
    public void export(HttpServletRequest request, String beginDate,String endDate,HttpServletResponse response, HttpSession session){
        try {
        	SessionInfo sessionInfo = (SessionInfo) session.getAttribute("sessionInfo");
            Long userID = sessionInfo.getUserId();
             
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("獎懲資訊列表");
            HSSFRow headRow = sheet.createRow(0);

            //這是一些要匯出列的標題
            String[] title = new String[] { "獎懲名稱","批准日期","檔名","檔案號","人數","具體人員"};
            for (int i = 0; i < title.length; i++) {
                headRow.createCell(i).setCellValue(title[i]);
            }
            //要匯出的資料物件集合
            //注意:這裡要寫成你自己的資料來源。
            List<ViewRewardExport> list = viewRewardService.queryList(beginDate,endDate,userID);
            HSSFCellStyle cellStyle = workbook.createCellStyle();  
            HSSFDataFormat format = workbook.createDataFormat();  
            cellStyle.setDataFormat(format.getFormat("@"));  
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (list != null && list.size() > 0) {
                for (ViewRewardExport log : list) {
                    HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
                    this.setCellStyle(workbook,dataRow.createCell(0),log.getRewardCodeName(),cellStyle);
                    this.setCellStyle(workbook,dataRow.createCell(1),sdf.format(log.getApproveDate()),cellStyle);
                    this.setCellStyle(workbook,dataRow.createCell(2),log.getFileName(),cellStyle);
                    this.setCellStyle(workbook,dataRow.createCell(3),log.getFileCode(),cellStyle);
                    this.setCellStyle(workbook,dataRow.createCell(4),log.getAmount().toString(),cellStyle);
                    this.setCellStyle(workbook,dataRow.createCell(5),log.getNames(),cellStyle);
                }
            }
            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) {
            	log.error("獎懲資訊列表Excel匯出出錯", e);
            }finally{
                if(workbook!=null){
                    workbook.close();
                }
                if(response.getOutputStream()!=null){
                    response.getOutputStream().close();
                }
            }
        } catch (Exception ce) {
        	log.error("獎懲資訊列表Excel匯出出錯", ce);
        }
    }
    //統一處理cell格式函式
    public HSSFCell setCellStyle(HSSFWorkbook workbook,HSSFCell cell,String value,HSSFCellStyle cellStyle){
        cell.setCellStyle(cellStyle);
        cell.setCellValue(value);
        return cell;
    }