spring boot中Excel文件下载踩坑大全

项目场景:Spring boot文件下载

调用接口下载spring boot工程的resources目录下的excel模板文件,非常常见的一个文件下载功能,但是却容易遇到很多坑,下面总结记录下。


问题一:下载的文件名称出现中文乱码的问题

解决方案:

response.setHeader("Content-Disposition",
                "attachment;filename=" + new String("下载模板".getBytes("UTF-8"), "ISO8859-1"));

说明:
这是网上最常见的解决方案,经过这样的修改后,在浏览器上调用get请求下载的文件确实没有出现文件名中文乱码了。
但是在swagger里面测试接口,下载的问题还是会出现中文乱码。

问题二:在swagger中测试下载接口,点击下载的文件,发现文件名是乱码的问题

这里我项目中使用的是springdoc-openapi-ui 1.5.9,基于的是openapi3.0的协议。
整体使用方式和界面和swagger类似。

swagger中下载的文件,点击开发后,文件名乱码问题:
在这里插入图片描述
解决方案:

response.setHeader("Content-Disposition", "attachment;fileName=" + 
URLEncoder.encode("线索导入模板.xlsx","utf8"));

说明:
通过URLEncoder.encode函数对文件名称处理后,无论是在浏览器调用GET请求下载文件,还是Swagger中调用下载接口,都不会出现文件名乱码问题。

问题三:下载的excel文件打开时总是提示部分内容有问题,尝试恢复。

在这里插入图片描述
在这里插入图片描述
问题原因:
一般有2种情况:
1、由于没有找到文件,下载的文件字节大小为0,这种情况文件完全打不开
2、读取的文件大小和元素文件的大小不一致,这种情况会提升自动修复。

解决办法:
网上最多的解决方案是主动在response的Header中设置Content-Length大小。但这种方式其实是错误的。文件的Content-Length其实可以从返回流中直接获取,并不需要用户主动去设置。这里的问题核心应该是思考:为什么下载的文件和元素文件的大小会不一致?
下面的2个获取inputStream的长度的API,只有在读取磁盘上具体文件中才比较适用。如果是jar包中的文件,是获取不到大小。

/加上设置大小
response.addHeader("Content-Length",String.valueOf(file.length()));
 //response.addHeader("Content-Length",String.valueOf(inputStream.available()));

问题四:采用BufferedInputStream缓冲流读写文件导致输出文件和原始文件体积差异的问题

由于下载的文件体积总是比元素文件体积大一点点,导致文件打开提示异常修复。

    outputStream = response.getOutputStream();
    bis = new BufferedInputStream(inputStream);
    //缓冲数组,每次读取1024
    byte[] buff = new byte[1024];
    while (bis.read(buff)!= -1) {
        //异常代码行
        outputStream.write(buff, 0, buff.length);
    }
    outputStream.flush(); 

原因分析:
出现问题的原因就是buff.length,数组声明后长度就是固定的,而不是获取里面读取的内容的字节长度,所以导致这里的buff.length的值始终是1024。

解决:

   outputStream = response.getOutputStream();
    bis = new BufferedInputStream(inputStream);
     //缓冲流,每次读取1024
    byte[] buff = new byte[1024];
    int readLength = 0;
     while (( readLength = bis.read(buff)) != -1) {
         //每次写入缓冲流buff读到的字节长度,而不是buff.length
         outputStream.write(buff, 0, readLength);
     }
    outputStream.flush();

问题五:开发环境下载成功,打成jar包发布到服务器上部署就出现下载失败问题

java.io.FileNotFoundException: class path resource [template/template.xlsx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file

原因:
Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它其实是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法无法正确获取文件。

解决:
通过ClassPathResource读取文件流

InputStream inputStream = getClass().getClassLoader().getResourceAsStream("template/template.xlsx");

完整代码

1、控制层代码

@Operation(summary = "下载模版",description = "下载模版")
@GetMapping("/download")
public void download(HttpServletResponse response){
    templateService.download(response);
}

2、下载方法实现

方式一:经典的缓冲流BufferedInputStream读取法,一般读取比较大的文件,优先考虑缓冲流读取方式
方式二:利用spring的FileCopyUtils工具类,小文件优先考虑此方式,代码更简单不易出错。

/**
 * 下载线索模板
 * @param response
 */
public void download(HttpServletResponse response) {
    InputStream inputStream = null;
    BufferedInputStream bis = null;
    OutputStream outputStream = null;
    try {     
        inputStream=getClass().getClassLoader().getResourceAsStream("template/template.xlsx");

        response.setContentType("application/octet-stream");
        response.setHeader("content-type", "application/octet-stream");
        //待下载文件名
        String fileName = URLEncoder.encode("模板.xlsx","utf8");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        outputStream = response.getOutputStream();
        //加上设置大小 下载下来的excel文件才不会在打开前提示修复
        //这里流的长度很难在开始读取前获取,特别是打成jar包后,读取inputStream长度经常失败
        //response.addHeader("Content-Length",String.valueOf(classPathResource.getFile().length()));
       //response.addHeader("Content-Length",String.valueOf(inputStream.available()));
         //方式一:经典的缓冲流BufferedInputStream读取法
         //   bis = new BufferedInputStream(inputStream);
             //缓冲流,每次读取1024
        //    byte[] buff = new byte[1024];
        //    int readLength = 0;
        //     while (( readLength = bis.read(buff)) != -1) {
        //         outputStream.write(buff, 0, readLength);
        //     }
        //     outputStream.flush();

         //方式二:利用spring的FileCopyUtils工具类
         if(inputStream!=null){
            byte[] results = FileCopyUtils.copyToByteArray(inputStream);
            outputStream.write(results);
            outputStream.flush();
        }
    } catch ( IOException e ) {
        log.error("文件下载失败,e");
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(bis);
    }
}

参考:https://blog.csdn.net/Hi_Boy_/article/details/107198371

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
要在Spring Boot导出Excel文件,可以使用Apache POI库。以下是一个简单的示例: 1. 添加POI依赖到pom.xml文件: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency> ``` 2. 创建一个Controller方法来生成Excel文件: ```java @GetMapping("/export") public void exportToExcel(HttpServletResponse response) throws IOException { // 创建工作簿 Workbook workbook = new XSSFWorkbook(); // 创建工作表 Sheet sheet = workbook.createSheet("Sheet 1"); // 创建表头行 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("Name"); headerRow.createCell(1).setCellValue("Age"); // 填充数据 List<Person> people = personService.getAllPeople(); int rowNum = 1; for (Person person : people) { Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(person.getName()); row.createCell(1).setCellValue(person.getAge()); } // 设置响应头 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=\"people.xlsx\""); // 输出Excel文件 OutputStream outputStream = response.getOutputStream(); workbook.write(outputStream); outputStream.close(); } ``` 3. 在上面的代码,我们首先创建了一个工作簿和一个工作表。然后创建表头行和填充数据行。最后,将响应设置为Excel文件,并将工作簿写入响应输出流。 4. 在上面的代码,我们使用了一个名为Person的类来存储人员信息。您需要根据您的数据模型调整代码。 这就是在Spring Boot导出Excel文件的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

斗者_2013

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值