axios({
method: 'get',
headers: { Authorization: `bearer ${window.store.state.token}` },
url: `${END_POINT}${obj.url}`,
responseType: 'blob',
}).then((res) => {
const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' });
const downloadElement = document.createElement('a');
const href = window.URL.createObjectURL(blob); // 创建下载的链接
downloadElement.href = href;
downloadElement.download = `${obj.label}.xls`; // 下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); // 点击下载
document.body.removeChild(downloadElement); // 下载完成移除元素
window.URL.revokeObjectURL(href); // 释放掉blob对象
});
第二种方案
clickExport() {
var weekData = {
startTime: this.startTime,
endTime: this.endTime,
companyId: this.weekCompanyId ? Number(this.weekCompanyId) : null,
departmentId: this.weekDepartmentId
}
// 方法
weeklyNumberExport(weekData).then(res => {
this.exportData(res, '每周人数表')
})
}
// 在调用统一方法
exportData(res, title) {
const link = document.createElement('a')
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
link.setAttribute('download', title + '.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
},
- 特别注意 api中需要
export function rosterExport(params) {
return request({
url: '/roster/listContractMessageExport',
method: 'get',
responseType: 'blob', /// 要单独添加
params
})
}
创建公共的下载方法
exportFactoryClue() {
const params = {
...this.page,
...this.searchParams,
...this.form,
searchType: this.form.timeType
}
exportSalesReportList(params).then((res) => {
// eslint-disable-next-line eqeqeq
if (res?.status == 504) {
this.$message.warning('服务响应超时,请联系管理员')
this.isExport2 = false
return
}
this.isExport2 = false
const time = this.Global.parseTime(new Date(), '{y}-{m}-{d}')
this.Global.downloadBlob(res.data, `销售报表列表${time}.xlsx`)
}).catch((err) => {
console.error(err)
this.isExport2 = false
})
},
// main.js
import Global from '@/base/global'
Vue.prototype.Global = new Global(Vue)
// base/global
class Global {
downloadBlob(data, fileName) { // 下载导出
const blob = new Blob([data])
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, fileName)
} else {
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
}
}
}
export default Global