1、后端返回的二进制流
当前端需要给后端传递参数或者需要headers中的Authorization时候,后端必须用二进制流的方式。
const file = await model.exportClient({ userIds }) // 调用接口,model.exportClient为封装好的接口let blob = new Blob([file], {type: 'application/xlsx;charset=utf-8', // application/xlsx // 这里写要下载的文件格式;charset=utf-8})let eleLink = document.createElement('a')const timeNow = dateFormat(new Date(), 'yyyyMMddHHmmss')eleLink.download = `客户信息${timeNow}.xlsx` // 这里写的是下载文件的名称eleLink.style.display = 'none'// 字符内容转变成blob地址// URL.createObjectURL(blob)会创建URL对象,返回一个下载文件的地址eleLink.href = URL.createObjectURL(blob)// 触发点击document.body.appendChild(eleLink)eleLink.click()// 释放URL对象URL.revokeObjectURL(eleLink.href)// 然后移除document.body.removeChild(eleLink)
2、当后端用cookie验证或不需要传递参数时候
此时有两种方式,直接调用接口url会默认重定向,也可以用form表单提交
①调用url
window.location.href = `${process.env.VUE_APP_BASE_URL}v1/user/export?userIds=${userIds}`
②form表单提交
这种方式可以在template中设置form元素,也可以用js动态生成form元素后挂载到body上。
const url = `${process.env.VUE_APP_BASE_URL}v1/user/export?userIds=${userIds}`let exportFrom = document.getElementById('_exportForm')if (!exportFrom) {exportFrom = document.createElement('form')exportFrom.setAttribute('id', '_exportForm')exportFrom.setAttribute('action', url)exportFrom.setAttribute('method', 'get')}document.body.appendChild(exportFrom)exportFrom.submit()
3、使用插件,前端生成excel
这种方式下,前端只请求数组数据,然后根据数组自己去生成excel文件模拟导出。
可以使用插件js-xlsx
npm说明地址:https://www.npmjs.com/package/js-xlsx-extended
也可以使用sheetjs插件。
