[java] Java Apache POI를 사용하여 Excel 파일에 셀 스타일 적용하기
Excel 파일을 다루는 작업에서 셀의 스타일을 적용해야 할 때가 있습니다. Java에서 Apache POI를 사용하면 간편하게 Excel 파일을 다룰 수 있으며, 스타일도 적용할 수 있습니다. 이번 포스트에서는 Java Apache POI를 사용하여 Excel 파일에 셀 스타일을 적용하는 방법에 대해 알아보겠습니다.
1. Apache POI 의존성 추가하기
먼저, Apache POI를 사용하기 위해 의존성을 추가해야 합니다. Maven을 사용한다면 pom.xml
파일에 다음 의존성을 추가해주세요.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
Gradle을 사용한다면 build.gradle
파일에 다음 의존성을 추가해주세요.
implementation 'org.apache.poi:poi:4.1.2'
의존성을 추가한 후 프로젝트를 갱신해주면 Apache POI를 사용할 준비가 되었습니다.
2. Excel 파일 생성 및 셀 스타일 적용하기
이제 Apache POI를 사용하여 Excel 파일을 생성하고, 셀 스타일을 적용해보겠습니다. 다음 예제를 참고해주세요.
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelCellStylingExample {
public static void main(String[] args) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// 스타일 생성
CellStyle headerStyle = workbook.createCellStyle();
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 12);
headerStyle.setFont(headerFont);
// 헤더 셀 스타일 적용
Row headerRow = sheet.createRow(0);
Cell headerCell = headerRow.createCell(0);
headerCell.setCellValue("Name");
headerCell.setCellStyle(headerStyle);
// 데이터 셀 생성 및 스타일 적용
Row dataRow = sheet.createRow(1);
Cell dataCell = dataRow.createCell(0);
dataCell.setCellValue("John Doe");
// Excel 파일 저장
try (FileOutputStream fileOut = new FileOutputStream("example.xlsx")) {
workbook.write(fileOut);
} catch (IOException e) {
e.printStackTrace();
}
}
}
위 예제는 Apache POI를 사용하여 Excel 파일을 생성하고, 첫 번째 행에 헤더 셀을 생성하고 스타일을 적용한 후, 두 번째 행에 데이터 셀을 생성하고 값을 입력하는 예제입니다. 생성한 Excel 파일은 example.xlsx
로 저장됩니다.
3. 실행 결과
위 예제를 실행하면 다음과 같은 Excel 파일이 생성됩니다.
Name |
---|
John Doe |
헤더 셀에는 굵은 글씨체와 크게 설정된 폰트 스타일이 적용되고, 데이터 셀에는 일반 글씨체가 적용됩니다.