[java] Java Apache POI를 사용하여 Excel 파일의 차트 생성하기

Excel 파일에서 데이터를 시각적으로 나타내는 차트는 정보를 쉽게 이해하고 분석할 수 있는 강력한 도구입니다. Java에서는 Apache POI라는 라이브러리를 사용하여 Excel 파일에 차트를 생성할 수 있습니다. 이번 포스트에서는 Java Apache POI를 사용하여 Excel 파일의 차트를 생성하는 방법을 알아보겠습니다.

Apache POI 라이브러리 다운로드 및 설정

먼저, Apache POI 라이브러리를 다운로드하고 프로젝트에 설정해야 합니다. Apache POI는 Apache 웹 사이트에서 다운로드할 수 있으며, 다운로드한 JAR 파일을 프로젝트의 빌드 패스에 추가해야 합니다.

Excel 파일 생성

Excel 파일을 생성하기 위해 Workbook 객체를 생성해야 합니다. 다음은 간단한 예제 코드입니다.

Workbook workbook = new XSSFWorkbook(); // XLSX 파일 생성
// Workbook workbook = new HSSFWorkbook(); // XLS 파일 생성
Sheet sheet = workbook.createSheet("Sheet1");

위 코드에서 주목해야 할 부분은 Workbook 객체를 생성할 때 사용하는 생성자입니다. XSSFWorkbook은 XLSX 파일을 생성하고, HSSFWorkbook은 XLS 파일을 생성합니다.

데이터 입력

차트를 나타내기 위해 데이터를 입력해야 합니다. 데이터는 RowCell 객체를 사용하여 특정 셀에 값을 입력하는 방식으로 처리할 수 있습니다.

Row row = sheet.createRow(0);
Cell cell1 = row.createCell(0);
cell1.setCellValue("Category");

Row row1 = sheet.createRow(1);
Cell cell2 = row1.createCell(0);
cell2.setCellValue("Data 1");

Row row2 = sheet.createRow(2);
Cell cell3 = row2.createCell(0);
cell3.setCellValue("Data 2");

위 예제 코드에서는 0번째 행에 “Category”라는 텍스트를 입력하고, 1번째 행에 “Data 1”을 입력하며, 2번째 행에 “Data 2”를 입력합니다.

차트 생성

이제 데이터를 입력했으므로 차트를 생성할 차례입니다. Apache POI에서는 다양한 유형의 차트를 생성할 수 있습니다. 예를 들어, 막대 그래프, 선 그래프, 원 그래프 등을 생성할 수 있습니다.

다음은 막대 그래프를 생성하는 예제 코드입니다.

Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 3, 10, 20); // 차트 위치 설정

Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.TOP_RIGHT);

LineChartData data = chart.getChartDataFactory().createLineChartData();

// 데이터 입력
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
ChartAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);

/* 데이터 설정 */

chart.plot(data, bottomAxis, leftAxis);

위 코드에서는 Drawing 객체를 사용하여 차트의 위치를 설정하고, Chart 객체를 생성합니다. 그 후 ChartLegendLineChartData 객체를 생성하여 차트에 필요한 데이터를 입력합니다.

Excel 파일 저장

차트를 생성한 후에는 Excel 파일을 저장해야 합니다. Workbook 객체의 write() 메서드를 사용하여 Excel 파일을 저장할 수 있습니다.

FileOutputStream outputStream = new FileOutputStream("chart.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();

위 코드에서는 FileOutputStream을 사용하여 파일을 생성하고, write() 메서드를 호출하여 Excel 파일을 저장합니다. 마지막으로 workbook 객체와 outputStream을 닫습니다.

이제 Java Apache POI를 사용하여 Excel 파일에 차트를 생성하는 방법을 알았습니다. 차트를 활용하여 데이터를 시각적으로 표현할 수 있으므로, 데이터 분석과 시각화에 유용하게 사용할 수 있습니다.

참고 자료