back-end/java

엑셀 파일 생성 및 다운로드

study-minjeong 2024. 8. 9. 10:00

Apache poi를 사용해서 엑셀에 데이터를 저장하는 방법을 알아보자!

poi는 아파치 소프트웨어 재단에서 만든 라이브러리로, 마이크로소프트 오피스 파일을 자바로 읽고 쓰는 기능을 제공한다.

 

 

1. 의존성 추가

implementation 'org.apache.poi:poi-ooxml:5.3.0'
implementation 'org.apache.poi:poi:5.3.0'

 

 

 

2. 주요 메소드

1) 워크북 생성

XSSFWorkbook wb = new XSSFWorkbook();

하나의 엑셀 파일이 된다.

 

 

2) 시트 생성

Sheet sheet = wb.createSheet("시트명");

하나의 엑셀 시트가 생성된다.

 

 

3) row, cell 생성

int rowCount = 0;
int cellCount = 0;

Row row = sheet.createRow(rowCount++);

Cell cell = row.createCell(cellCount++);

 

 

4) cell에 값 입력

cell.setCellValue("값");

 

 

5) 헤더 설정

response.setContentType("application/octet-stream/");
response.setHeader("Content-Disposition","attachment; filename=\"test.xlsx\"");

HTTP 헤더 부분의 content-type을 저장한다.

브라우저에서 파일 저장/다른 이름으로 저장할 수 있게 하고, 파일 이름을 지정해준다.

 

 

6) 엑셀 저장

wb.write(response.getOutputStream());

 

 

 

엑셀 다운로드를 하는 기초적인 부분을 알아보았다.

다음에는 셀 병합, 폰트 및 스타일 설정하는 방법을 정리해야겠다~~