当前位置:   article > 正文

springboot+vue EasyExcel 后端返回文件流,前端浏览器下载【导出为例】_easyexcel返回文件流

easyexcel返回文件流

需求: 后端返回文件流格式,前端进行下载,这边以导出数据为例

如图文件流
请添加图片描述
前端处理:

请求路由上加上 responseType:‘blob’

在这里插入图片描述

文件流处理

res 为请求后端接口返回文件流 结果

    const blob = new Blob([res.data], {
            type: 'application/vnd.ms-excel'
          });
          let link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.setAttribute('download', '工作日志.xlsx');
          link.click();
          link = null;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

后端主要逻辑

@Override
    public void exportList(ExportQuery query, HttpServletResponse response, HttpServletRequest request) {
        //查询数据源
        List<WorkLogInfo>  exportList = new ArrayList();
        //具体从数据库查询,这边删除无关紧要查询代码
        。。。。。。
        
        try {
            String fileName = "工作日志";

            String userAgent = request.getHeader("User-Agent");

            if (userAgent.contains(ConstantValue.MSIE) || userAgent.contains(ConstantValue.TRIDENT)) {
                // 针对IE或者以IE为内核的浏览器:
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                // 非IE浏览器的处理:
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName + ".xlsx"));
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", -1);
            response.setCharacterEncoding("UTF-8");
            EasyExcel.write(response.getOutputStream(), WorkLogDto.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("导出列表")
                    .doWrite(exportList);
        } catch (Exception e) {
            log.info("导出失败");
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/842467
推荐阅读
相关标签
  

闽ICP备14008679号