[java] Apache POI를 사용하여 Excel 파일의 테두리 읽기

Apache POI는 Java로 작성된 라이브러리로, Microsoft Office 포맷으로 된 문서를 읽고 쓸 수 있게 해줍니다. 이번 글에서는 Apache POI를 사용해서 Excel 파일의 셀 테두리를 읽어오는 방법에 대해 알아보겠습니다.

1. Maven 종속성 추가

먼저, Maven 프로젝트의 pom.xml 파일에 Apache POI의 종속성을 추가해야 합니다. 아래의 의존성을 dependencies 태그 내에 추가합니다.

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

2. 테두리 읽기 코드 작성

Excel 파일의 테두리를 읽기 위해서는 org.apache.poi.ss.usermodel.CellStyle 클래스의 getBorderBottom(), getBorderTop(), getBorderLeft(), getBorderRight() 메서드를 사용합니다. 아래는 테두리를 읽어오는 예제 코드입니다.

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

import java.io.FileInputStream;
import java.io.IOException;

public class ExcelBorderReader {
    public static void main(String[] args) {
        String filePath = "경로/파일명.xlsx";

        try (Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath))) {
            Sheet sheet = workbook.getSheetAt(0);
            Row row = sheet.getRow(0);
            Cell cell = row.getCell(0);
            
            CellStyle cellStyle = cell.getCellStyle();
            BorderStyle borderBottom = cellStyle.getBorderBottom();
            BorderStyle borderTop = cellStyle.getBorderTop();
            BorderStyle borderLeft = cellStyle.getBorderLeft();
            BorderStyle borderRight = cellStyle.getBorderRight();
            
            System.out.println("Bottom border: " + borderBottom);
            System.out.println("Top border: " + borderTop);
            System.out.println("Left border: " + borderLeft);
            System.out.println("Right border: " + borderRight);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 코드에서 filePath 변수는 읽어올 Excel 파일의 경로와 파일명을 지정해주면 됩니다. 코드의 주석을 참고하여 필요한 부분을 변경하십시오.

3. 실행 및 결과 확인

위의 코드를 실행하면 지정한 Excel 파일의 첫 번째 셀의 테두리 정보가 출력됩니다. 테두리의 상태는 BorderStyle 열거형으로 확인할 수 있으며, NONE, THIN, MEDIUM, THICK 등 다양한 값이 존재합니다.

이제 Apache POI를 사용하여 Excel 파일의 테두리를 읽어올 수 있는 방법을 알게 되었습니다. Excel 파일을 읽고 처리하는 데에는 Apache POI가 매우 유용한 라이브러리입니다.

참고 자료