[java] Apache POI를 이용한 Excel 시트 설정

Excel 파일을 생성하거나 편집할 때, Apache POI는 자바 언어를 통해 강력하고 유연한 인터페이스를 제공합니다. 특히, Apache POI를 사용하여 Excel 시트를 설정하는 방법을 알아보겠습니다.

필요한 의존성 추가하기

먼저, Apache POI를 사용하기 위해 프로젝트의 의존성에 아래의 Maven 종속성을 추가해야 합니다.

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

Excel 시트 생성하기

아래의 코드를 사용하여 Apache POI를 이용해 Excel 시트를 생성할 수 있습니다.

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

public class ExcelExample {
    public static void main(String[] args) {
        Workbook workbook = new XSSFWorkbook(); // 빈 워크북 생성
        Sheet sheet = workbook.createSheet("Sheet1"); // Sheet1 생성

        // 셀에 데이터 입력하기
        Row row = sheet.createRow(0); // 첫 번째 행 생성
        Cell cell = row.createCell(0); // 첫 번째 셀 생성
        cell.setCellValue("Hello, World!"); // 셀에 값 설정

        // Excel 파일로 저장하기
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("example.xlsx");
            workbook.write(fileOutputStream); // 파일로 쓰기
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 코드는 빈 워크북을 생성한 후, Sheet1을 생성하고 첫 번째 행에 “Hello, World!” 값을 입력하는 예제입니다. 마지막으로, workbook.write()를 호출하여 Excel 파일로 저장합니다.

Excel 파일 열기 및 시트 설정하기

아래의 코드는 기존의 Excel 파일을 열고 시트를 설정하는 예제입니다.

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

public class ExcelExample {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        Workbook workbook = null;
        try {
            fileInputStream = new FileInputStream("example.xlsx");
            workbook = WorkbookFactory.create(fileInputStream);

            Sheet sheet = workbook.getSheet("Sheet1"); // Sheet1 가져오기
            Row row = sheet.getRow(0); // 첫 번째 행 가져오기
            Cell cell = row.getCell(0); // 첫 번째 셀 가져오기

            System.out.println(cell.getStringCellValue()); // 셀 값 출력

            fileInputStream.close();
        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

위의 코드는 “example.xlsx” 파일을 열고 Sheet1에서 첫 번째 셀의 값을 가져와 출력하는 예제입니다. WorkbookFactory.create() 메소드를 사용하여 파일을 열고, getStringCellValue()로 셀의 값을 읽을 수 있습니다.

Apache POI를 사용하면 자바로 Excel 파일을 효율적으로 처리할 수 있습니다. Apache POI에는 다양한 기능과 설정 방법이 있으며, 관련 문서를 참조하여 더 많은 기능을 알아보시기 바랍니다.

참고자료