[java] Java Apache POI를 사용하여 Excel 파일의 셀 텍스트 정렬 설정하기

Apache POI는 Java에서 Excel 파일을 다루기 위한 라이브러리입니다. 이 라이브러리를 사용하면 Java로 Excel 파일을 생성, 수정, 읽기 및 쓰기를 할 수 있습니다. 이번에는 Apache POI를 사용하여 Excel 파일의 셀 텍스트 정렬을 설정하는 방법에 대해서 알아보겠습니다.

1. Apache POI 라이브러리 추가하기

먼저, 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>

2. 셀 텍스트 정렬 설정하기

Apache POI를 사용하여 Excel 파일의 셀 텍스트 정렬을 설정하려면 다음 단계를 따르면 됩니다.

먼저, Workbook 객체를 생성합니다.

Workbook workbook = new XSSFWorkbook();

다음으로, 원하는 텍스트 정렬을 설정할 CellStyle 객체를 생성합니다.

CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);

위의 예제에서는 셀 텍스트를 가운데로 정렬하는 방법을 보여줍니다. setAlignment 메서드의 매개변수를 다른 값으로 설정하여 텍스트를 원하는 방식으로 정렬할 수 있습니다.

마지막으로, 특정 셀에 생성한 CellStyle을 적용합니다. 이를 위해 Cell 객체를 생성하고 setCellStyle 메서드를 사용합니다.

Cell cell = row.createCell(0);
cell.setCellValue("Hello, World!");
cell.setCellStyle(cellStyle);

위의 예제에서는 첫 번째 열의 첫 번째 셀에 “Hello, World!”라는 텍스트를 입력한 다음, 생성한 CellStyle을 적용하여 텍스트를 가운데로 정렬합니다.

완성된 예제 코드

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelCellAlignmentExample {
    public static void main(String[] args) throws IOException {
        // Create a new workbook
        Workbook workbook = new XSSFWorkbook();

        // Create a new sheet
        Sheet sheet = workbook.createSheet("Cell Alignment Example");

        // Create a new row
        Row row = sheet.createRow(0);

        // Create a new cell style and set the alignment to center
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        // Create a new cell and set the cell style
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello, World!");
        cell.setCellStyle(cellStyle);

        // Write the workbook to a file
        FileOutputStream fileOut = new FileOutputStream("alignment_example.xlsx");
        workbook.write(fileOut);
        fileOut.close();

        // Close the workbook
        workbook.close();
    }
}

위의 예제 코드는 Apache POI를 사용하여 Excel 파일을 생성하고 첫 번째 셀의 텍스트를 가운데로 정렬한 뒤 파일로 저장하는 예제입니다.

결론

Apache POI를 사용하면 Java에서 Excel 파일을 다룰 수 있습니다. 이번 예제에서는 Apache POI를 사용하여 Excel 파일의 셀 텍스트 정렬을 설정하는 방법을 살펴보았습니다. 위의 예제 코드를 참고하여 필요에 맞게 Excel 파일을 생성 및 텍스트 정렬을 설정해보세요.

참고