前端实现文件导出功能

92 阅读1分钟

项目中有很多地方用到table组件,需将数据导出为excel文件,目前是后端返回一个excel文件流,前端直接解析实现导出功能,以下为功能主要实现代码。

function exportExcel(){
    //responseType: 'blob'这个参数很关键,通过该参数解析响应数据为blob
    axios.get('接口地址',params,{responseType: 'blob'}).then(res=>{
        blobToExcel(res)
})}



function blobToExcel(res){
let blob = new Blob([res.data], { type: res.data.type })
const aLink = window.document.createElement('a')
aLink.setAttribute('href', window.URL.createObjectURL(blob))
aLink.setAttribute('target', '_blank')
aLink.setAttribute('download', fileName) // 设置下载文件名称aLink.click()
}