vue 엑셀 다운로드

miyaongg·2023년 7월 1일
0
post-thumbnail

요구사항

  • BO 화면에서 차트나 회원 정보 데이터를 엑셀로 다운로드 할 수 있도록 구현

서버 통신은 axios 라이브러리를 사용했고 엑셀 다운로드 버튼 클릭 시 파일 다운로드 api를 호출하도록 했다.

API 호출

this.$axios.get('api url', { responseType: 'blob' })
.then(response => {
	if(response.success) {
    	return response
    }
}

파일 다운로드

const url = window.URL.createObjectURL(new Blob([response.data], { type: response.headers['content-type'] })) }

const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'fileName.xlsx')
document.body.appendChild(link)
link.click()

파일명 추출

const disposition = response.headers['content-disposition']
const fileName = decodeURI(
	disposition
    .match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)[1]
    .replace(/['"]/g, "")
 )



주의
{ responseType: 'blob' }을 빼면 엑셀 파일이 깨지거나 열리지 않기 때문에 꼭 넣어주어야 함


Blob이란?

Blob(Binary Large Object)
텍스트 혹은 이진 데이터를 담고 있는 큰 객체로, 주로 이미지, 오디오, 비디오 등 다른 타입에 비해 용량이 클 가능성이 높은 타입들을 관리할 떄 많이 사용된다.

큰 용량의 데이터의 경우 이진 데이터가 많은 저장소에 퍼져있을 것이고, 한 페이지에 다 넣어져있을 수 없어서 잘게 쪼개져 각자 다른 주소의 페이지에 나뉘어져 있을 것이다.
이렇게 퍼져있는 데이터를 하나의 Entity로 편하게 관리할 수 있도록 도와주는 역할을 한다.

profile
Front-End Developer

0개의 댓글