상세 컨텐츠

본문 제목

[JAVA] Excel - POI (XSSFWorkbook Example)

Spring/POI

by Chan.94 2023. 2. 21. 20:48

본문

반응형

POI

아파치 소프트웨어 재단에서 만든 라이브러리로 Microsoft Office 파일을 자바 언어로 읽고 쓰는 기능 제공한다.
주로 Word, Excel, Power Point 파일을 지원한다.

 

POI라이브러리를 사용하여 Excel을 다루어보자.

 

Workbook 종류

HSSF : Excel 2007 하위버전(.xls) 파일 포맷을 사용할 때 사용
XSSF : Excel 2007 (.xlsx) 파일 포맷을 사용할 때 사용
SXSSF : 대용량 엑셀 파일을 출력할 때 사용

XSSF, SXSSF 차이

  • XSSF
    - 읽기, 쓰기가 가능하다.
    - 메모리에 파일데이터를 쌓아두고 사용하기 때문에 용량이 큰 경우 Out Of Memory 에러가 발생한다. 

  • SXSSF
    - 쓰기만 가능하다.
    - 임시파일을 중간중간 생성하여 메모리를 적게 사용하기 때문에 XSSF보다 매우 큰 엑셀 파일을 생성할 수 있다.
    - XSSF는 전체 행에 대한 컨트롤이 가능하지만 SXSSF는 지정된 행 (window size)에 관해서만 컨트롤이 가능해서 메모리를 적게 사용한다.

 

용량이 작은 파일을 읽고 쓰는 데는 둘 중 아무거나 사용해도 무방하다.

몇 십만건의 데이터를 엑셀에 저장하는 것처럼 대용량이라면 이야기는 달라진다. Memory leak을 생각해야 한다.

XSSF는 workbook을 생성하는 시점에 엑셀파일내용 전체를 메모리에 올리기 때문에 Memory leak이 발생할 가능성이 크다.

 

XSSFWorkbook 사용방법에 대해 정리하겠다.

SXSSFWorkbook에 대한 내용은 'POI (SXSSFWorkbook Example)' 을 참조바란다.

HSSFWorkbook과 XSSFWorkbook을 함께 사용하는 방법은 'POI (WorkbookFactory)'을 참조바란다.


MAVEN 추가

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

 

XSSFWorkbook Write Example

 

workbook 생성

XSSFWorkbook workbook = new XSSFWorkbook();

sheet 생성

XSSFSheet sheet = workbook.createSheet("SheetName");

row 생성

XSSFRow row = sheet.createRow(index);

cell생성

XSSFCell cell = row.createCell(index);

cell 값 설정

cell.setCellValue("value");

workbook 저장

FileOutputStream fos = new FileOutputStream(new File("경로"));
workbook.write(fos);
fos.close();

Write Example

String rootPath = "C:/DevLog/";

//생성일자
Calendar cal = Calendar.getInstance() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddhhmmsss");
String date = dateFormat.format(cal.getTime());
String time = timeFormat.format(cal.getTime());
String directoryPath = String.format("%s%s", rootPath, date);
String excelFullPath = String.format("%s/devlog_%s.xlsx", directoryPath, time);
File directory = new File(directoryPath);	//디렉토리 경로

//디렉토리생성
if(!directory.exists()) {
	directory.mkdir();
}

//workbook 생성
XSSFWorkbook workbook = new XSSFWorkbook();
//sheet 생성
XSSFSheet sheet = workbook.createSheet("DevLog");

/*데이터 생성*/
int nRowCnt = 9;
int nColCnt = 9;
for(int nRow = 0 ; nRow <= nRowCnt ; nRow++) {
	//row 생성
	XSSFRow row = sheet.createRow(nRow);
	for(int nCol = 0 ; nCol <= nColCnt ; nCol++) {
		XSSFCell cell = row.createCell(nCol);
		cell.setCellValue(String.format("%s x %s = %s", nRow, nCol, nRow * nCol));
	}
}
//workbook 저장
FileOutputStream fos = new FileOutputStream(new File(excelFullPath));
workbook.write(fos);
fos.close();

workbook을 다루기 전에는 File Object를 사용할 수 있어야 한다.

File Object에 대한 내용은 'File Object 기본 사용법'을 참고 바란다.

 

실행결과


XSSFWorkbook Read Example

workbook 생성

File file = new File("excel경로");
XSSFWorkbook workbook = new XSSFWorkbook(file);

sheet 객체

XSSFSheet sheet = workbook.getSheet("sheet명");

sheet의 row 개수

sheet.getPhysicalNumberOfRows();

row 객체

XSSFRow row = sheet.getRow(index);

row의 cell 개수

row.getPhysicalNumberOfCells();

cell 객체

XSSFCell cell = row.getCell(index);

cell 값

cell.toString();

Read Example

String excelFullPath = "C:/DevLog/20230221/devlog_202302210817056.xlsx";

File file = new File(excelFullPath);

//workbook 생성
XSSFWorkbook workbook = new XSSFWorkbook(file);
//sheet 가지고오기
XSSFSheet sheet = workbook.getSheet("DevLog");
//row 개수
int nMaxRowCnt = sheet.getPhysicalNumberOfRows();
for(int nRow = 0 ; nRow < nMaxRowCnt ; nRow++) {
	//row Object
	XSSFRow row = sheet.getRow(nRow);
	//col 개수
	int nMaxColCnt = row.getPhysicalNumberOfCells();
	
	for(int nCol = 0 ; nCol < nMaxColCnt ; nCol++) {
		XSSFCell cell = row.getCell(nCol);
		System.out.println(cell.toString());
	}
	System.out.println("-------------------------------------");
}

실행결과

0 x 0 = 0
0 x 1 = 0
0 x 2 = 0
0 x 3 = 0
0 x 4 = 0
0 x 5 = 0
0 x 6 = 0
0 x 7 = 0
0 x 8 = 0
0 x 9 = 0
-------------------------------------
1 x 0 = 0
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
-------------------------------------
2 x 0 = 0
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
-------------------------------------
3 x 0 = 0
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
-------------------------------------
4 x 0 = 0
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
-------------------------------------
5 x 0 = 0
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
-------------------------------------
6 x 0 = 0
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
-------------------------------------
7 x 0 = 0
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
-------------------------------------
8 x 0 = 0
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
-------------------------------------
9 x 0 = 0
9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
-------------------------------------
반응형

'Spring > POI' 카테고리의 다른 글

[JAVA] Excel - POI (WorkbookFactory)  (5) 2023.02.26
[JAVA] Excel - POI (SXSSFWorkbook Example)  (10) 2023.02.22

관련글 더보기

댓글 영역

>