상세 컨텐츠

본문 제목

Java Excel 읽기, 쓰기 (Apache POI)

프로그램 언어/Java

by husks 2023. 2. 7. 15:46

본문

반응형

다음은 Apache POI 라이브러리를 사용하여 Excel 파일을 읽고 쓰기 위한 Java의 예제입니다.

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

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelReadWrite {
  public static void main(String[] args) throws IOException {
    // 엑셀 읽기
    FileInputStream inputStream = new FileInputStream("example.xlsx");
    XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
    XSSFSheet sheet = workbook.getSheetAt(0);
    for (Row row : sheet) {
      for (Cell cell : row) {
        System.out.print(cell.getStringCellValue() + " ");
      }
      System.out.println();
    }
    workbook.close();
    inputStream.close();

    // 엑셀 쓰기
    FileOutputStream outputStream = new FileOutputStream("example.xlsx");
    workbook = new XSSFWorkbook();
    sheet = workbook.createSheet();
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    cell.setCellValue("Hello");
    workbook.write(outputStream);
    workbook.close();
    outputStream.close();
  }
}

 

참고: 프로젝트에 Apache POI 라이브러리를 추가해야 합니다. pom.xml에 다음 종속성을 추가하거나(Maven을 사용하는 경우) 라이브러리를 다운로드하여 클래스 경로에 추가하면 됩니다.

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

 

 

반응형

관련글 더보기

댓글 영역