관리 메뉴

IT.FARMER

java excle 대용량 다운로드 poi 본문

JAVA

java excle 대용량 다운로드 poi

아이티.파머 2019. 9. 19. 13:23
반응형

자바 excel dowonload 시에 많은양의 데이터를 다운로드 하다보면 OOM 에 봉착할수 있다.

이를 해결하기 위해서는 POI 스트리빙방식으로 코드를 작성한다.

 

생성자로 부터 직접 건수를 지정하여, 지정된 건수가 되면 temp 파일에 flush 하는 방법이 있으며,

수동으로 temp file에 flush 하는 방법이 존재한다.

 

Workbook 특징

  • HSSF : EXCEL 2007 이전 버전(.xls)에서 사용하는 방식
  • XSSF : EXCEL 2007 이후 버전(2007포함 .xlsx)에서 사용하는 방식
  • SXSSF : XSSF Streaming Version으로 메모리를 적게 사용하여 대용량 엑셀 다운로드에 주로 사용되는 방식

 

SXSSF 방식->생성자 방식에서의 기본 flush 크기는 100 이며, -1 지정시 무제한이다. 

쓰기전용이며 읽기는 불가능하다. 

 

읽기 전용에 데이터를 쓰기시도할때 다임과 같은 오류가 발생된다.

java.lang.IllegalArgumentException: Attempting to write a row[0] in the range [0,999] that is already written to disk.

0~999까지 1,000 row 까지 저장되어 있기때문에 1001번부터 쓰기가 가능하다.

 

저장사이즈 설정 사용법에는 두가지가 있다. 생성자 설정과,  사용자 정의 에의한 중간 저장 방식 

 

1. 생성자 방식 예제

SXSSFWorkbook wb = new SXSSFWorkbook(100); // turn off auto-flushing and accumulate all rows in memory
    Sheet sh = wb.createSheet();
    for (int rownum = 0; rownum < 100000; rownum++) {
      Row row = sh.createRow(rownum);
      for (int cellnum = 0; cellnum < 10; cellnum++) {
        Cell cell = row.createCell(cellnum);
        String address = new CellReference(cell).formatAsString();
        cell.setCellValue(address);
      }
    }

    FileOutputStream out = new FileOutputStream("d:/sxssf2.xlsx");
    wb.write(out);
    out.close();

    // dispose of temporary files backing this workbook on disk
    wb.dispose();

 

2. 사용자 정의 중간 flush

 public void bigDataSheet() throws Exception {

    SXSSFWorkbook wb = new SXSSFWorkbook(-1); // turn off auto-flushing and accumulate all rows in memory
    Sheet sh = wb.createSheet();
    for (int rownum = 0; rownum < 100000; rownum++) {
      Row row = sh.createRow(rownum);
      for (int cellnum = 0; cellnum < 10; cellnum++) {
        Cell cell = row.createCell(cellnum);
        String address = new CellReference(cell).formatAsString();
        cell.setCellValue(address);
      }

      // manually control how rows are flushed to disk
      if (rownum % 100 == 0) {
        ((SXSSFSheet) sh).flushRows(100); // retain 100 last rows and flush all others

        // ((SXSSFSheet)sh).flushRows() is a shortcut for ((SXSSFSheet)sh).flushRows(0),
        // this method flushes all rows
      }

    }

    FileOutputStream out = new FileOutputStream("d:/sxssf.xlsx");
    wb.write(out);
    out.close();

    // dispose of temporary files backing this workbook on disk
    wb.dispose();

  }

 

 

 

 

 

 

 

The New Halloween Document

The New Halloween Document How to use the HSSF API Capabilities This release of the how-to outlines functionality for the current

poi.apache.org

 

 

반응형

'JAVA' 카테고리의 다른 글

Jmeter performance configuration  (0) 2019.12.04
Intellij 2019.2 build tool gradle default  (0) 2019.11.07
java null safe stream 생성 방법  (0) 2019.09.05
병렬처리와 동시성  (0) 2019.05.27
CompletableFuture  (0) 2019.05.16