[java] Apache POI를 이용한 Excel 차트 생성

Apache POI는 자바로 Microsoft Office 파일을 조작하는 라이브러리입니다. 이 라이브러리를 사용하여 Excel 문서에서 차트를 생성하는 방법에 대해 알아보겠습니다.

1. 의존성 추가

먼저 Maven 또는 Gradle 등의 의존성 관리 도구를 사용하여 Apache POI를 프로젝트에 추가해야 합니다. Maven을 사용하는 경우 pom.xml 파일에 다음 의존성을 추가해주세요:

<dependencies>
  <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
  </dependency>
  <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
  </dependency>
</dependencies>

Gradle을 사용하는 경우 build.gradle 파일에 다음 의존성을 추가해주세요:

dependencies {
    implementation 'org.apache.poi:poi:4.1.2'
    implementation 'org.apache.poi:poi-ooxml:4.1.2'
}

2. Excel 파일 생성

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelChartExample {

    public static void main(String[] args) {
        // 새로운 워크북 생성
        Workbook workbook = new XSSFWorkbook();
        
        // 시트 생성
        Sheet sheet = workbook.createSheet("차트 예시");
        
        // 데이터 생성
        Row row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("항목");
        row1.createCell(1).setCellValue("값");
        
        Row row2 = sheet.createRow(1);
        row2.createCell(0).setCellValue("A");
        row2.createCell(1).setCellValue(10);
        
        Row row3 = sheet.createRow(2);
        row3.createCell(0).setCellValue("B");
        row3.createCell(1).setCellValue(20);
        
        Row row4 = sheet.createRow(3);
        row4.createCell(0).setCellValue("C");
        row4.createCell(1).setCellValue(30);
        
        // 차트 생성
        Drawing<?> drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 3, 1, 8, 10);
        Chart chart = drawing.createChart(anchor);
        ChartLegend legend = chart.getOrCreateLegend();
        legend.setPosition(LegendPosition.BOTTOM);
        
        LineChartData data = chart.getChartDataFactory().createLineChartData();
        ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
        ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
        
        ChartDataSource<String> categories = DataSources.fromStringCellRange(sheet, new CellRangeAddress(1, 3, 0, 0));
        ChartDataSource<Number> values = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 3, 1, 1));
        
        data.addSeries(categories, values);
        chart.plot(data, bottomAxis, leftAxis);
        
        // 파일 저장
        try (OutputStream fileOut = new FileOutputStream("chart_example.xlsx")) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // 메모리 해제
        workbook.close();
    }
}

3. 실행 및 결과 확인

위의 예제 코드를 실행하면 현재 디렉토리에 chart_example.xlsx 파일이 생성됩니다. 이 파일을 열어보면 “차트 예시”라는 이름의 시트에 차트가 생성된 것을 확인할 수 있습니다.

이렇게 Apache POI를 사용하여 Excel 파일에 차트를 생성하는 방법을 알아보았습니다. 참고로, Excel 파일에는 다양한 종류의 차트를 생성할 수 있으며, POI 라이브러리의 다양한 클래스와 메소드를 사용하여 더 세부적인 조작이 가능합니다.

더 자세한 내용은 Apache POI 공식 문서를 참고해주세요.