1.配置请求数据
const myObj = {
method: "get",
url: "/v1/invoice/export_invoice_customer",
fileName: "未开发票明细.xlsx"
//data
};
await exportMethod(myObj);
2.编写导出excel表函数
// 需要引入项目中的axios来发送请求 import axios from '**'
export function exportMethod(data) {
return new Promise((resolve, reject) => {
let submitData = {
method: data.method,
url: `${data.url}`,
responseType: 'blob'
}
if (data.method == 'post' || data.method == 'put') submitData.data = data.data
else submitData.params = data.data
axios(submitData).then((res) => {
if (res.data?.type == 'application/json') {
return reject()
}
console.log('res',res)
// 创建一个a标签元素
const link = document.createElement('a')
// 使用返回的文本流数据生成一个Blod实例
let blob = new Blob([res.data], { type: 'application/octet-stream' })
// 将a标签在页面中隐藏
link.style.display = 'none'
// 将文本实例blod转换成url
link.href = URL.createObjectURL(blob)
// 使用a标签的download属性下载文件,修改文件的名称
link.download = data.fileName // 下载后文件名
// 添加a标签元素
document.body.appendChild(link)
// 点击a标签元素下载excel表格
link.click()
// 删除a标签元素
document.body.removeChild(link)
resolve()
}).catch(error => {
// 当前的请求类型(responseType)是blob, 所以接口返回的数据类型也是blob, 需要对错误信息进行转换处理
const reader = new FileReader();
reader.readAsText(error.response.data, 'utf-8');
reader.onload = () => {
Message.error(JSON.parse(reader.result).msg)
};
})
})
}