导出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;
	}
原文地址:https://www.cnblogs.com/jcjssl/p/9335877.html