Apache POI는 Java에서 Excel 파일을 다루는 데 사용되는 라이브러리입니다. 이 라이브러리를 사용하면 Excel 파일을 생성, 수정, 읽기 등 다양한 작업을 할 수 있습니다. 이번 포스트에서는 Apache POI를 사용하여 Excel 파일의 셀 주석을 읽어오는 방법에 대해 알아보겠습니다.
필요한 의존성 추가하기
먼저, Maven 프로젝트를 사용한다면 pom.xml
파일에 다음 의존성을 추가해야 합니다.
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
</dependencies>
Gradle 프로젝트를 사용한다면 build.gradle
파일에 다음 의존성을 추가해야 합니다.
dependencies {
implementation 'org.apache.poi:poi:4.1.2'
}
Excel 파일의 셀 주석 읽기
Excel 파일의 셀 주석을 읽기 위해서는 XSSFWorkbook
또는 HSSFWorkbook
객체를 생성해야 합니다. 이후 getSheetAt()
메서드를 사용하여 원하는 시트를 선택하고, getRow()
메서드로 해당 행을 가져온 후, getCellComment()
메서드를 사용하여 셀 주석을 가져올 수 있습니다.
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadExcelCellComment {
public static void main(String[] args) throws IOException {
// 읽어올 Excel 파일 경로 설정
String filePath = "path/to/your/excel/file.xls";
// Excel 파일을 읽기위한 FileInputStream 생성
FileInputStream fis = new FileInputStream(filePath);
// Excel 파일 열기
Workbook workbook = WorkbookFactory.create(fis);
// 첫 번째 시트 선택
Sheet sheet = workbook.getSheetAt(0);
// 첫 번째 행 선택
Row row = sheet.getRow(0);
// 첫 번째 셀 주석 가져오기
Cell cell = row.getCell(0);
Comment comment = cell.getCellComment();
// 셀 주석 출력
if (comment != null) {
System.out.println(comment.getString().getString());
}
// FileInputStream과 Workbook 닫기
fis.close();
workbook.close();
}
}
위 예제에서는 Excel 파일 경로를 filePath
변수에 설정한 후, FileInputStream
으로 Excel 파일을 열고, 원하는 시트(Sheet
)와 행(Row
), 셀(Cell
)을 선택하여 셀 주석(Comment
)을 가져옵니다. 마지막으로 가져온 셀 주석을 출력합니다.
즉, Comment comment = cell.getCellComment();
코드를 통해 셀 주석을 가져올 수 있습니다. 가령, 주석이 존재하지 않는 경우 comment
변수는 null
이 됩니다.
위 방법을 이용하여 Apache POI를 사용하여 Excel 파일의 셀 주석을 읽어오는 방법을 살펴보았습니다. 추가적으로 Apache POI의 다른 기능들도 알아보시면 더욱 다양한 작업을 수행할 수 있을 것입니다.
참고 자료
- Apache POI 공식 웹사이트: http://poi.apache.org/
- Apache POI GitHub 저장소: https://github.com/apache/poi