💡 회사에서 근태 내역 엑셀 파일 다운로드 기능을 구현한 과정을 기록하려고 한다! (백엔드에서 제공한 api 응답 값이 엑셀 파일 그 자체라는 가정하에 구현하는 과정이다!)
export function GetAttendanceRecordsDownload(format: string, params: { teamId: number; date: string }) {
return axios.get(`api URL`, { params, responseType: 'blob' }); // 응답 타입을 바이너리(blob)로 지정
}
const downloadExcel = () => {
if (!currentTeamId || !selectedDate) return;
GetAttendanceRecordsDownload('xlsx', { teamId: currentTeamId, date: format(selectedDate, 'yyyy-MM') })
.then((res) => {
const blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}); // 응답으로 받은 데이터를 기반으로 Blob 객체를 생성하고 엑셀 MIME 타입 명시
const url = window.URL.createObjectURL(blob); // Blob 데이터를 URL로 변환
const a = document.createElement('a'); // <a> 태그를 동적으로 생성
a.href = url; // href에 Blob URL 할당
a.download = `원하는 이름.xlsx`; // 다운로드될 파일 이름 설정
document.body.appendChild(a); // <a> 태그를 문서에 추가
a.click(); // 클릭 이벤트를 발생시켜 자동 다운로드 유도
a.remove(); // <a> 태그를 문서에서 제거
window.URL.revokeObjectURL(url); // 브라우저에 생성한 Blob URL을 해제하여 메모리 누수 방지
})
.catch(() => {
// 에러 발생 시 처리
});
};