Apache POI를 이용한 Excel 사용자 정의 스타일 구현

Apache POI에서 Excel 생성은 HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook 세 가지 방식으로 구현 가능합니다.
HSSFWorkbook은 최대 65,533행까지 지원하며(.xls 확장자), XSSFWorkbook은 1,048,576행 처리 가능하나(.xlsx) 대용량 시 메모리 오버플로우 위험이 있습니다.
SXSSFWorkbook은 지정 행 초과 시 디스크에 자동 저장되어 메모리 문제를 해결합니다.
POI의 행/열 인덱스는 0부터 시작하며, 셀 병합 시 이 점에 유의해야 합니다.
다음은 Excel 생성 및 스타일 설정 구현 예시입니다:
// Excel 워크북 생성
SXSSFWorkbook excelDoc = new SXSSFWorkbook();
excelDoc.setCompressTempFiles(true); // 임시 파일 압축 활성화

String filePath = "result_data.xlsx";
Path outputPath = Paths.get(filePath);
Files.createDirectories(outputPath.getParent());

generateExcelContent(excelDoc);

try (FileOutputStream fos = new FileOutputStream(filePath)) {
    excelDoc.write(fos);
} finally {
    excelDoc.dispose(); // 임시 파일 정리
}
void generateExcelContent(SXSSFWorkbook excelDoc) throws IOException {
    SXSSFSheet dataSheet = excelDoc.createSheet("데이터시트");
    
    // 컬럼 너비 설정
    for (int colIdx = 0; colIdx < 6; colIdx++) {
        dataSheet.setColumnWidth(colIdx, 4500);
    }
    
    // 데이터 행 생성
    SXSSFRow dataRow = dataSheet.createRow(0);
    SXSSFCell valueCell = dataRow.createCell(0);
    valueCell.setCellValue("데이터값");
    valueCell.setCellStyle(configureCellStyle(excelDoc));
}
CellStyle configureCellStyle(SXSSFWorkbook excelDoc) {
    CellStyle customStyle = excelDoc.createCellStyle();
    customStyle.setFont(createFontStyle(excelDoc));
    customStyle.setAlignment(HorizontalAlignment.RIGHT);
    customStyle.setVerticalAlignment(VerticalAlignment.TOP);
    customStyle.setWrapText(true);
    
    // 테두리 설정
    customStyle.setBorderTop(BorderStyle.THIN);
    customStyle.setBorderBottom(BorderStyle.DASHED);
    return customStyle;
}
Font createFontStyle(SXSSFWorkbook excelDoc) {
    Font textFont = excelDoc.createFont();
    textFont.setFontName("맑은 고딕");
    textFont.setFontHeightInPoints((short) 12);
    textFont.setBold(true);
    textFont.setColor(IndexedColors.DARK_BLUE.getIndex());
    return textFont;
}
// 특정 열 범위 스타일 적용
void applyColumnStyle(SXSSFWorkbook excelDoc, SXSSFSheet targetSheet, 
                      int startRow, int endRow, int columnIdx, short fillColor) {
                          
    CellStyle rangeStyle = excelDoc.createCellStyle();
    if (fillColor != -1) {
        rangeStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        rangeStyle.setFillForegroundColor(fillColor);
    }
    
    for (int rowIdx = startRow; rowIdx <= endRow; rowIdx++) {
        Row currentRow = targetSheet.getRow(rowIdx);
        if (currentRow == null) break;
        Cell targetCell = currentRow.getCell(columnIdx);
        targetCell.setCellStyle(rangeStyle);
    }
}

태그: apache-poi Excel-생성 Java-스프레드시트 셀-스타일링 SXSSFWorkbook

7월 8일 05:38에 게시됨