[java] Java Apache POI를 사용하여 Excel 파일의 데이터 찾기

Java Apache POI는 Excel 파일을 조작하는 데 사용되는 강력한 라이브러리입니다. 이 라이브러리를 사용하여 Excel 파일에서 특정 데이터를 찾는 방법을 알아보겠습니다.

준비사항

먼저, Apache POI를 프로젝트에 추가해야 합니다. Maven을 사용하는 경우 pom.xml 파일에 다음 의존성을 추가합니다:

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

Gradle을 사용하는 경우 build.gradle 파일에 다음 의존성을 추가합니다:

implementation 'org.apache.poi:poi:5.0.0'

Excel 파일에서 데이터 찾기

1. Excel 파일 로드하기

Excel 파일에서 데이터를 찾으려면 먼저 해당 파일을 로드해야 합니다. 다음 코드 예제는 data.xlsx 파일을 로드하는 방법을 보여줍니다:

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

public class ExcelDataSearch {
    public static void main(String[] args) {
        try {
            // Excel 파일 로드
            Workbook workbook = WorkbookFactory.create(new File("data.xlsx"));

            // 작업할 시트 선택
            Sheet sheet = workbook.getSheetAt(0);

            // 여기에 데이터를 찾는 코드를 작성합니다.

            // 메모리 해제
            workbook.close();
        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
        }
    }
}

2. 데이터 찾기

Excel 파일을 로드한 후에는 원하는 데이터를 찾을 수 있습니다. Apache POI는 Cell 객체를 사용하여 셀의 내용을 읽어올 수 있습니다. 다음 코드 예제는 특정 셀에서 데이터를 읽는 방법을 보여줍니다:

Row row = sheet.getRow(rowNum); // 행 번호(rowNum)에 해당하는 행 가져오기
Cell cell = row.getCell(cellNum); // 열 번호(cellNum)에 해당하는 셀 가져오기

if (cell != null) {
    switch (cell.getCellType()) {
        case STRING:
            String value = cell.getStringCellValue();
            System.out.println(value);
            break;
        case BOOLEAN:
            boolean value = cell.getBooleanCellValue();
            System.out.println(value);
            break;
        case NUMERIC:
            double value = cell.getNumericCellValue();
            System.out.println(value);
            break;
    }
}

위의 코드를 사용하여 원하는 셀에서 데이터를 읽을 수 있습니다.

3. 데이터 검색

특정 데이터를 찾으려면 Excel 파일의 모든 셀을 반복하며 조건을 검사해야 합니다. 다음 코드 예제는 Excel 파일에서 특정 값을 찾는 방법을 보여줍니다:

String searchValue = "Apple";

int rowCount = sheet.getLastRowNum();
int colCount = sheet.getRow(0).getLastCellNum();

for (int i = 0; i <= rowCount; i++) {
    Row row = sheet.getRow(i);
    for (int j = 0; j < colCount; j++) {
        Cell cell = row.getCell(j);
        if (cell != null && cell.getCellType() == CellType.STRING) {
            String cellValue = cell.getStringCellValue();
            if (cellValue.equals(searchValue)) {
                System.out.println("좌표: (" + i + ", " + j + ")");
                System.out.println("값: " + cellValue);
            }
        }
    }
}

위의 코드를 사용하여 Excel 파일에서 특정 값을 검색할 수 있습니다.

결론

Java Apache POI를 사용하면 Excel 파일에서 쉽게 데이터를 찾을 수 있습니다. 이 라이브러리는 다양한 기능을 제공하기 때문에 다른 작업에도 유용하게 사용할 수 있습니다.

참고 문서: Apache POI 공식 문서