-
SpringBoot 초간단 엑셀 다운로드 기능 구현(Apache POI)Spring 2024. 10. 25. 15:28반응형
기본적으로 다른 환경은 구성되어있다고 가정하고 빠르게 살펴보겠다.
build.gradle - poi의존성 추가
implementation 'org.apache.poi:poi-ooxml:5.2.3' // 최신 버전으로 대체 가능
ExcelDownloadController 파일 생성
package com.example.exceltest.controller; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.io.ByteArrayOutputStream; import java.io.IOException; @Controller public class ExcelDownloadController { @GetMapping("/") public String index(Model model) { return "index"; // index.html 파일 반환 } @GetMapping("/api/excel/download") public ResponseEntity<byte[]> downloadExcel() throws IOException { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sample Sheet"); // 엑셀 헤더 생성 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("ID"); headerRow.createCell(1).setCellValue("Name"); headerRow.createCell(2).setCellValue("Age"); // 엑셀 데이터 생성 Row dataRow = sheet.createRow(1); dataRow.createCell(0).setCellValue(1); dataRow.createCell(1).setCellValue("John"); dataRow.createCell(2).setCellValue(29); // 각 열의 너비 자동 조정 sheet.autoSizeColumn(0); // ID 열 sheet.autoSizeColumn(1); // Name 열 sheet.autoSizeColumn(2); // Age 열 // 엑셀 파일을 ByteArrayOutputStream에 작성 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); workbook.close(); // HTTP 응답 헤더 설정 HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=sample.xlsx"); headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK); } }
간단한 화면 구현
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>엑셀 다운로드</title> </head> <body> <h1>엑셀 파일 다운로드</h1> <a th:href="@{/api/excel/download}" class="button">다운로드</a> </body> </html>
서버를 실행 한뒤 각자 지정한 url로 접속 후 다운로드 버튼을 클릭한다면 excel이 다운로드 된다.
이와같이 우리가 설정하였던 값들이 다운 되는 것을 확인 할 수 있다.
반응형'Spring' 카테고리의 다른 글
Vo 와 Dao 차이점 파헤치기 (0) 2024.12.03 초간단 SpringBoot DB데이터 Excel 다운로드 (0) 2024.10.25 [Spring boot] - 소셜로그인(Naver,Google) + 일반로그인 구현 (0) 2024.07.23 [SpringBoot] - 구글, 네이버 소셜로그인 구현 설정 (0) 2024.07.23 [SpringBoot] - 소셜로그인작동 원리 (0) 2024.07.22