vue3+axios请求导出excel文件

在Vue 3中使用axios请求导出Excel文件,可以发送一个GET或POST请求,并设置响应类型为blob或arraybuffer,然后使用new Blob()构造函数创建一个二进制文件,最后使用URL.createObjectURL()生成一个可以下载的链接。

先看代码

复制代码
import axios from 'axios';
 
// 导出Excel文件的函数
export function exportExcel() {
  const url = '/api/export'; // 替换为你的接口地址
  axios({
    method: 'get',
    url: url,
    responseType: 'blob', // 重要!设置响应类型为blob或arraybuffer
  })
  .then(response => {
    // 创建一个新的Blob对象,设置文件类型
//response.data是后端返回的文件流数据,如果response是文件流就直接用response,根据后端返回实际情况而定
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel;charset=UTF-8' });
    // 创建一个指向新Blob对象的URL
    const url = window.URL.createObjectURL(blob);
    // 创建一个a标签用于下载
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'export.xls'); // 设置下载文件名
    document.body.appendChild(link);
    // 触发下载
    link.click();
    // 清理并移除元素和对象URL
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  })
  .catch(error => {
    console.error('导出Excel失败:', error);
  });
}

后端返回的数据是一个二进制数据流,可以console.log(response)打印一下响应数据,查看数据是不是Blob类型,如果不是的话可能会出现乱码、undefined等情况

以arraybuffer类型为准的post请求,以下是后端返回数据截图,这里response的值是文件流

后端返回的数据

响应拦截器获取到的数据

打印的response数据

如果前端得到的数据结构跟上面截图一样,大概是没有问题的,如果出现中文乱码、undefined等情况,可以检查一下是否在请求时设置了响应类型,blob和arraybuffer还是有区别的,blob不行就试试arraybuffer

相关推荐
摘星编程1 天前
React Native for OpenHarmony 实战:Linking 链接处理详解
javascript·react native·react.js
胖者是谁1 天前
EasyPlayerPro的使用方法
前端·javascript·css
EndingCoder1 天前
索引类型和 keyof 操作符
linux·运维·前端·javascript·ubuntu·typescript
摘星编程1 天前
React Native for OpenHarmony 实战:ImageBackground 背景图片详解
javascript·react native·react.js
hhzz1 天前
EasyPoi的核心映射工具:@Excel注解详解
java·服务器·excel·springboot·easypoi
摘星编程1 天前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe5561 天前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
WHS-_-20221 天前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
摘星编程1 天前
React Native for OpenHarmony 实战:GestureResponderSystem 手势系统详解
javascript·react native·react.js
lili-felicity1 天前
React Native for OpenHarmony 实战:加载效果的实现详解
javascript·react native·react.js·harmonyos