id="excelGo" 버튼을 클릭했을 때 Excel 파일다운로드

반응형

아래는 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 파일 다운로드

 

반응형

Designed by JB FACTORY