[java] Java Apache POI를 사용하여 Excel 파일의 특정 행 가져오기

Apache POI는 Java에서 Excel 파일을 다루기 위한 라이브러리 중 하나입니다. 이 라이브러리를 사용하면 Java 코드로 Excel 파일을 읽고 쓸 수 있습니다. 이번에는 Apache POI를 사용하여 Excel 파일에서 특정 행을 가져오는 방법에 대해 알아보겠습니다.

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

먼저, 프로젝트에 Apache POI 라이브러리를 추가해야 합니다. 다음과 같이 Maven을 사용하는 경우, pom.xml 파일에 아래의 의존성을 추가합니다.

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

2. Excel 파일 열기 및 특정 행 가져오기

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

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

public class ExcelReader {

    public static void main(String[] args) {
        try (FileInputStream file = new FileInputStream("path/to/excel/file.xlsx")) {
            Workbook workbook = new XSSFWorkbook(file);
            Sheet sheet = workbook.getSheetAt(0);

            // 원하는 행의 인덱스
            int rowIndex = 0;

            Row row = sheet.getRow(rowIndex);

            // 행의 각 셀의 값을 가져옴
            for (Cell cell : row) {
                CellType cellType = cell.getCellType();
                if (cellType == CellType.STRING) {
                    String cellValue = cell.getStringCellValue();
                    System.out.println("Cell Value: " + cellValue);
                } else if (cellType == CellType.NUMERIC) {
                    double cellValue = cell.getNumericCellValue();
                    System.out.println("Cell Value: " + cellValue);
                }
            }

            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제 코드에서는 XSSFWorkbook 클래스를 사용하여 Excel 파일을 열고, getSheetAt() 메서드를 사용하여 첫 번째 시트를 가져옵니다. 가져온 시트에서 특정 행의 인덱스를 지정하여 getRow() 메서드를 호출합니다. 그리고 행의 각 셀의 값을 가져와서 출력합니다.

3. 실행 결과 확인하기

위의 예제 코드를 실행하면, 지정한 Excel 파일에서 첫 번째 행의 값을 가져와서 콘솔에 출력합니다.

Cell Value: Value 1
Cell Value: Value 2
Cell Value: Value 3

이와 같이 Apache POI를 사용하여 Excel 파일의 특정 행을 가져오는 방법을 알아봤습니다. 직접 작성한 코드를 실행해보고, 다양한 Excel 파일에 대해 테스트해보세요.

참고 자료