서비스 운영 중 사용자들 편의를 위해 엑셀 파일 다운로드 기능을 제공할 일이 생겨 학습한 내용을 기록한다.
라이브러리 추가
둘 중 하나만 추가하면 된다.
HSSFWorkbook은 .xls 확장자, XSSWorkbook은 .xlsx 확장자 전용이라고 한다.
나는 .xlsx인 두 번째 라이브러리만 추가했다.
implementation 'org.apache.poi:poi:5.2.2' // HSSFWorkbook 사용 implementation 'org.apache.poi:poi-ooxml:5.2.2' // XSSFWorkbook 사용
컨트롤러
@Controller @RequiredArgsConstructor @RequestMapping("/excels") public class ExcelController { private final ExcelService excelService; @GetMapping public void download(HttpServletResponse response) throws IOException { excelService.download(response); } }
HttpServletResponse를 인자로 받아야한다.
서비스
@Service @Transactional(readOnly = true) public class ExcelService { public void download(HttpServletResponse response) throws IOException { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("첫번째 시트"); int rowNum = 0; Cell cell = null; Row row = null; // Header int cellNum = 0; row = sheet.createRow(rowNum++); cell = row.createCell(cellNum++); cell.setCellValue("번호"); cell = row.createCell(cellNum++); cell.setCellValue("이름"); // Body for (int i = 1; i <= 3; i++) { cellNum = 0; row = sheet.createRow(rowNum++); cell = row.createCell(cellNum++); cell.setCellValue(i); cell = row.createCell(cellNum++); cell.setCellValue("학생" + i); } // Download response.setContentType("ms-vnd/excel"); response.setHeader("Content-Disposition", "attachment;filename=student.xlsx"); try { wb.write(response.getOutputStream()); } finally { wb.close(); } } }
구조는 간단하다. Header, Body에 각자 상황에 맞게 적절한 내용을 입력하면 된다.
+) 마지막 wb.write(), wb.close()를 try-finally로 감싸주지 않으면 openxml4jexception이 발생한다.
API 호출
크롬같은 웹 브라우저에 다음 url을 입력해보자.
http:localhost:8080/excels

엑셀 파일이 다운받아진다.
내용도 잘 입력된 것을 볼 수 있다.

지금까지 엑셀 다운로드 API에 대해 알아보았다. 이 밖에 스타일 등 여러 설정들을 지원하는 것 같다.
현재는 객체들의 리스트를 쫙 뽑아주는 용도로 사용하고 있는데 상당히 유용한 것 같다.
참고자료
https://jhhan009.tistory.com/67
'java > spring' 카테고리의 다른 글
[Spring] AWS S3 파일 압축해서 다운로드 - 여러가지 방법 비교분석 (2) | 2022.08.05 |
---|---|
[Spring] AWS S3 객체 삭제 (0) | 2022.08.04 |
[Spring] request multipart file size 조정 (0) | 2022.08.03 |
[Spring] MariaDB connection 끊김 (0) | 2022.08.03 |
[Spring] Failed to validate connection (0) | 2022.08.03 |