導出excel表格(按模板導出)


html代碼:

/**
  * 業務數據信息下載
  *
  * @param response
  * @param fundReconciliationQueryVo
  * @param request
*/
@RequestMapping(value = "/downloadBusinessInfo")
public ResponseEntity<byte[]> downloadBusinessInfo(HttpServletResponse response, FundReconciliationQueryVo fundReconciliationQueryVo, HttpServletRequest request) {
        ResponseEntity<byte[]> responseEntity = null;
        //獲取前台額外傳遞過來的查詢條件
        if (log.isDebugEnabled()) {
            log.debug("fundReconciliationQueryVo:{}", fundReconciliationQueryVo);
        }
        try {
            String fileName = "businessInfoModel.xlsx";
            ClassPathResource resource = new ClassPathResource(fileName);
            InputStream inputStream = resource.getInputStream();
            Workbook workbook = ReadExcelUtil.getWorkbook(inputStream, fileName);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            List<BusinessDataDto> businessInfoList = fundReconciliationService.downloadBusinessInfo(fundReconciliationQueryVo);
            for (BusinessDataDto businessDataDto : businessInfoList) {
                if ("1".equals(businessDataDto.getAccountStatus())) {
                    businessDataDto.setAccountStatus("已確認");
                } else if ("2".equals(businessDataDto.getAccountStatus())) {
                    businessDataDto.setAccountStatus("需要處理");
                } else if ("3".equals(businessDataDto.getAccountStatus())) {
                    businessDataDto.setAccountStatus("已收賬");
                } else {
                    businessDataDto.setAccountStatus("未匹配");
                }
            }
            //生成EXCEL XLSX格式
            this.businessInfoExportData(workbook, businessInfoList, byteArrayOutputStream);

            String downFileName = java.net.URLEncoder.encode("業務數據信息.xlsx", "UTF-8");
            //設置響應頭讓瀏覽器正確顯示下載
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", downFileName);
            responseEntity = new ResponseEntity<>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseEntity;
    }
    public static Workbook getWorkbook(InputStream is, String fileName) throws IOException {
        Workbook workbook = null;
        try {
            if (fileName.endsWith(EXTENSION_XLS)) {
                workbook = new HSSFWorkbook(is);
            } else if (fileName.endsWith(EXTENSION_XLSX)) {
                workbook = new XSSFWorkbook(is);
            }

        } catch (FileNotFoundException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } finally {
            is.close();
 }
 public void businessInfoExportData(Workbook workbook, List<BusinessDataDto> businessInfoList, OutputStream outputStream) {
        //EXCEL列
        List<List<Object>> rows = new ArrayList<>();
        //從給定數據獲取指定列作為EXCEL列數據
        for (BusinessDataDto businessDataDto : businessInfoList) {
            List<Object> row = new ArrayList<>();
            //序號
            row.add(businessDataDto.getIndexNum());
            //發票抬頭
            row.add(businessDataDto.getName());
            //報銷單號
            row.add(businessDataDto.getReportNo());
            //單號
            row.add(businessDataDto.getBillsNo());
            //結算金額
            row.add(new BigDecimal(businessDataDto.getOrderAmount()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            //支付時間
            if (Lang.isEmpty(businessDataDto.getAtsPayDate())) {
                row.add(businessDataDto.getAtsPayDate());
            } else {
                row.add(DateUtils.formatDate(businessDataDto.getAtsPayDate(), GlobalContants.DateFormat.YYYY_MM_DD_HH_MM_SS));
            }
            //狀態
            row.add(businessDataDto.getAccountStatus());
            rows.add(row);
        }
        XSSFWorkbook xwb = excelService.businessAndFinancialInfoExcelForXLSX(workbook, rows);
        try {
            xwb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                xwb.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

excelService

       /**
	 * 業務數據信息/財務到賬信息下載
	 * @param rows 數據行
	 * @return
	 */
	public XSSFWorkbook businessAndFinancialInfoExcelForXLSX(Workbook workbook, List<List<Object>> rows) {
		XSSFWorkbook xwb = (XSSFWorkbook) workbook;
		XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(0);
		//設置字體
		XSSFFont font = xwb.createFont();
		font.setFontName("宋體");//設置字體名稱
		font.setFontHeightInPoints((short)12);//設置字號
		//設置單元格格式
		XSSFCellStyle style = xwb.createCellStyle();
		style.setFont(font);
		style.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
		style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); //垂直居中
		style.setWrapText(true);//自動換行
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下邊框
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左邊框
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上邊框
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右邊框
		// 寫入數據行
		XSSFRow row;//行
		XSSFCell cell;//單元格
		int rowIdx = 1;
		for(List<Object> dr : rows) {
			row = sheet.createRow(rowIdx);
			for(int di=0; di < dr.size(); di++) {
				cell = row.createCell(di);
				cell.setCellStyle(style);
				String cellValue = "";
				if(Lang.isEmpty(dr.get(di))){
					cellValue = "";
				}else{
					cellValue = dr.get(di)+"";
				}
				cell.setCellValue(new XSSFRichTextString(cellValue));
			}
			rowIdx ++;
		}
		return xwb;
	}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM