728x90
Java에서 엑셀 파일을 읽고, 값을 추가한 후 다시 다운로드할 수 있도록 하는 기능을 구현하려면 Apache POI 라이브러리를 사용할 수 있습니다.
다음과 같은 흐름으로 구현할 수 있습니다:
- 사용자가 업로드한 Excel 파일을 Java에서 읽기
- 특정 데이터를 추가하거나 수정
- 수정된 Excel 파일을 클라이언트에 다시 제공 (다운로드)
주요 라이브러리:
- Apache POI: Excel 파일을 읽고 쓰는 기능을 제공
- Spring Boot: 파일 업로드 및 다운로드 API 구현
이제 코드를 작성해보겠습니다.
생성 중단됨
Java에서 Apache POI 라이브러리를 사용하여 Excel 파일을 읽고 값을 추가한 후 다시 다운로드할 수 있도록 하는 예제를 만들어보겠습니다.
1. 필요 라이브러리 추가
Maven 프로젝트라면 pom.xml에 Apache POI 의존성을 추가하세요.
<dependencies>
<!-- Apache POI (Excel 읽고 쓰기) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
</dependencies>
2. Java 코드 작성
다음은 Excel 파일을 읽고, 데이터를 추가한 후, 수정된 파일을 다운로드하는 코드입니다.
ExcelService.java (Excel 파일 처리 서비스)
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Service
public class ExcelService {
public ResponseEntity<InputStreamResource> processExcel(MultipartFile file) throws IOException {
// 1. 엑셀 파일 읽기
Workbook workbook = new XSSFWorkbook(file.getInputStream());
Sheet sheet = workbook.getSheetAt(0); // 첫 번째 시트 가져오기
// 2. 값 추가 (마지막 행 다음에 새로운 데이터 추가)
int lastRowNum = sheet.getLastRowNum();
Row newRow = sheet.createRow(lastRowNum + 1);
Cell newCell = newRow.createCell(0);
newCell.setCellValue("새로운 값 추가!");
// 3. 엑셀을 다시 저장
ByteArrayOutputStream out = new ByteArrayOutputStream();
workbook.write(out);
workbook.close();
// 4. 파일을 HTTP 응답으로 반환 (다운로드)
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
InputStreamResource resource = new InputStreamResource(in);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=modified.xlsx")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
}
ExcelController.java (컨트롤러)
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/excel")
public class ExcelController {
private final ExcelService excelService;
public ExcelController(ExcelService excelService) {
this.excelService = excelService;
}
@PostMapping("/upload")
public ResponseEntity<InputStreamResource> uploadExcel(@RequestParam("file") MultipartFile file) {
try {
return excelService.processExcel(file);
} catch (Exception e) {
return ResponseEntity.internalServerError().build();
}
}
}
3. 실행 방법
- Spring Boot 애플리케이션을 실행합니다.
- Postman 또는 프론트엔드에서 파일 업로드 요청을 보냅니다.
- POST http://localhost:8080/excel/upload
- multipart/form-data로 파일 (file 필드) 업로드
- 서버에서 처리된 Excel 파일을 다운로드받을 수 있습니다.
4. 주요 기능 설명
- MultipartFile을 받아서 Apache POI를 사용해 엑셀을 읽고 값 추가.
- 수정된 엑셀 파일을 HTTP 응답으로 제공하여 다운로드 가능하게 만듦.
- Spring Boot REST API 방식으로 업로드 & 다운로드 구현.
LIST
'Develop > JAVA' 카테고리의 다른 글
Spring Interceptor를 활용한 페이지 이동 추적 및 제어 (1) | 2025.03.26 |
---|---|
[Java] 봉인 클래스(Sealed Classes): Java 17의 혁신적인 기능과 예제까지 (0) | 2025.03.19 |
[Java] 특정 달의 마지막 날짜와 요일 구하기 (2) | 2025.02.19 |
Spring Framework의 @Scheduled 어노테이션 완벽 가이드 (1) | 2025.02.14 |
[Java] REST API 호출 및 JSON 데이터를 DTO로 파싱하는 방법 (3) | 2025.01.08 |