프로그래밍/Java

[Java] 엑셀(Excel) 파일 읽기 (Feat.poi)

코딩중독 2023. 11. 19. 22:15

Maven 추가

pom.xml 에 dependencies를 추가

org.apache.poi

    <dependencies>
        <!-- 엑셀 읽기 필수 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- 엑셀 읽기 필수 -->

        <!-- 엑셀 읽기 에러 처리 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.1</version>
        </dependency>
        <!-- 엑셀 읽기 에러 처리 -->
    </dependencies>

 

Load Maven Changes (Ctrl + Shift + O)

Maven 변경사항을 적용

 

엑셀 경로 (프로젝트 최상위)

 

엑셀 읽어오기

FileInputStream file = new FileInputStream(new File("example.xlsx"));

 

FileInputStream 클래스는 파일을 바이트 단위로 입력받아 출력할 수 있다.

 

워크북 생성, 시트 지정

Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheetAt(0);

 

읽어온 엑셀 파일을 워크북에 지정하고 작업할 시트를 정한다.

작업할 시트가 여러개라면 0, 1, 2... 지정할 수 있다.

 

행별로 각 셀 읽기 (다중 반복문)

for (Row row : sheet) {
    for (Cell cell : row) {
    
    // 셀 타입별 데이터 읽기 추가

    }
}

 

첫 번째 for문 : 지정한 시트에서 데이터가 포함된 모든 행 반복

두 번째 for문 : 선택된 행의 모든 셀 반복

 

데이터 타입별로 출력하기

switch (cell.getCellType()) {
    case NUMERIC:	// 숫자타입
        if (DateUtil.isCellDateFormatted(cell)) {	// 날짜형식
            Date dateValue = cell.getDateCellValue();
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = dateFormat.format(dateValue);
            System.out.print(formattedDate + "\t");
        } else {	// 날짜형식을 제외한 숫자 형식
            double numericValue = cell.getNumericCellValue();
            if (numericValue == Math.floor(numericValue)) {
                int intValue = (int) numericValue;
                System.out.print(intValue + "\t");
            } else {
                System.out.print(numericValue + "\t");
            }
        }
        break;
    case STRING:	// 문자타입
        String stringValue = cell.getStringCellValue();
        System.out.print(stringValue + "\t");
        break;
    case BOOLEAN:	// Boolean타입
        boolean booleanValue = cell.getBooleanCellValue();
        System.out.print(booleanValue + "\t");
        break;
    case FORMULA:	// 수식타입
        String formulaValue = cell.getCellFormula();
        System.out.print(formulaValue + "\t");
        break;
    case ERROR:
    case _NONE:
    case BLANK:
    default:
        System.out.print("\t");
        break;
}

 

엑셀 원본

1 2 3 4 5
A B C D E
지민 RM 정국
35.6 32.6 25.9 45.8 25.1
2023-10-10 2023-10-18 2023-10-28 2023-11-06 2023-11-15

 

출력형태

 

주의!

데이터를 타입별로 분기를 주지 않고 그냥 출력하면 다음과 같은 결과가 나온다.

for (Row row : sheet) {
    for (Cell cell : row) {
        System.out.print(cell.toString() + "\t");
    }
    System.out.println();
}
file.close();

 

 

마치며...

데스크톱에 있는 엑셀 파일로 작업을 하기 위해서는 처음 엑셀을 읽어오는 부분에서 데스크톱의 경로를 적어주면 된다.

FileInputStream file = new FileInputStream(new File("C:\\Users\\admin\\Desktop\\example.xlsx"));

 

잘못된 내용이 있다면 댓글 부탁드립니다!