一: 在响应拦截器对响应数据进行处理
代码如下:
if (response.data instanceof ArrayBuffer) {
return response;
}
if (response.data instanceof Blob) {
return response;
}
二: 必须设置 响应类型为blob
代码如下:
responseType: 'blob',
三: 接口调用下载导出的方法
代码如下:
// 下载导出 txt Excel
const handleDownload = (id: string, type: string, fileName: string) => {
reportsDownload({ id: id }).then((res) => {
console.log("res Blob", res);
const blob =
type === "excel"
? new Blob([res.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
})
: new Blob([res.data], { type: "text/plain" }); // 转换为二进制
const blobUrl = URL.createObjectURL(blob); // 转换为二进制 的链接
const link = document.createElement("a"); // 创建a标签
link.href = blobUrl; // 下载链接
link.download = fileName; // 下载的文件名
document.body.appendChild(link);
link.click();
});
};
这里出现个问题: 导出txt文件类型后再导出excel类型的文件,但是会自动变成txt 类型的
看看 link 是不是对应的类型,会有影响导出的文件类型的
四:不调用接口,前端将表格数据导出表格为 excel
1. 给 el-table 添加 ref
2. 方法如下:
exportToExcel() {
const table = this.$refs.table.$el;
const workbook = XLSX.utils.table_to_book(table, { raw: true });
const wbout = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
let tableName = ''; // 自定义名字
tableName ? tableName + ".xlsx" : "表格.xlsx";
this.downloadExcel(wbout, tableName);
},
downloadExcel(buffer, filename) {
const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
link.href = url;
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
},
记录,做专属的备忘录!
—— 安夏