react下载excel文件

256 阅读1分钟

需求:后端返回文件流对象,前端操作触发浏览器下载行为

注意:在请求中要写上responseType为blob

image.png

blob的类型也有很多种,注意和后端沟通

image.png

完整代码:

      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 = decodeURIComponent(
        res.headers['content-disposition'].split('filename=')[1],
      );
      //也可以前端命名
      //downloadElement.download = `总览报告_${moment(dateString[0]).format('YYYYMMDD')}_${moment(
          dateString[1],
        ).format('YYYYMMDD')}.xlsx`; //下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); //点击下载
      document.body.removeChild(downloadElement); //下载完成移除元素
      window.URL.revokeObjectURL(href); //释放掉blob对象