id="excelGo" 버튼을 클릭했을 때 Excel 파일다운로드
- 📕 Programing/jQuery
- 2025. 7. 18.
반응형
아래는 id="excelGo" 버튼을 클릭했을 때 jQuery로 AJAX 호출하여 Excel 파일 다운로드 하는 코드 예시입니다.
클릭 시 서버에 요청을 보내고, 응답을 처리하도록 구성했습니다.
✅ HTML 코드 (이미 제공됨)
<button class="filter-btn" data-filter="excellent" id="excelGo">우수</button>
✅ jQuery AJAX 코드
$(document).ready(function () {
$('#excelGo').on('click', function () {
$.ajax({
url: '/excel/download', // 요청 보낼 URL
type: 'GET', // 메서드 (GET/POST 등)
xhrFields: {
responseType: 'blob' // 파일 다운로드용 응답 처리
},
success: function (data, status, xhr) {
// 응답 헤더에서 파일명 추출
const disposition = xhr.getResponseHeader('Content-Disposition');
let filename = 'excel.xlsx';
if (disposition && disposition.indexOf('filename=') !== -1) {
filename = disposition.split('filename=')[1].replace(/"/g, '');
}
// Blob으로 파일 생성 및 다운로드
const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
},
error: function () {
alert('엑셀 다운로드 중 오류가 발생했습니다.');
}
});
});
});
✅ 백엔드 URL 매칭 확인
- 위 jQuery는 /excel/download로 요청을 보냅니다.
- 이 URL은 앞서 작성한 Spring Boot 컨트롤러의 이 부분과 일치해야 합니다:
@GetMapping("/download")
public void downloadExcel(HttpServletResponse response) throws IOException
예: @RequestMapping("/excel") + @GetMapping("/download") → /excel/download
✅ 결과
- 사용자가 “우수” 버튼 클릭
→ 서버에서 엑셀 파일 생성
→ 클라이언트가 자동으로 excel.xlsx 파일 다운로드
반응형
'📕 Programing > jQuery' 카테고리의 다른 글
| [프론트엔드 팁] 테이블 <td> 긴 텍스트, 깔끔하게 표시하고 툴팁으로 전체 보기 (4) | 2025.07.25 |
|---|---|
| 마우스 로딩표시 (0) | 2023.12.26 |
| [jQuery] match() 함수(특정 문자 포함 여부) (0) | 2023.02.09 |
| [jQuery] checkbox에 체크된 값들만 가져오기 / 전체 선택|해제 (0) | 2023.02.03 |
| [jQuery Plugin ] magnify - 이미지 확대 | 축소 등 (0) | 2021.10.18 |