JAVA下载Excel文件之后无法打开,提示损坏

resources 目录下放模板 excel 文件,通过接口下载后,可以正常下载,但打不开。

问题: springboot 项目简单的下载excel 模板功能,模板放在resources/template/目录中

java 复制代码
public void downloadItemBatch(HttpServletResponse response) throws IOException {
        String fileName = "商品信息.xlsx";
        String path = "templates/" + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }

代码挺简单,一运行,也挺顺利,很快就把文件下好了。点开看看,提示我可能是内存不足,文件无法打开,而且下载的文件比templates里的文件要大。

看了很多帖子,试了很多方法,最后发现,pom文件里加个东西就行了

XML 复制代码
<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-resources-plugin</artifactId>
	<version>2.7</version>
	<configuration>
		<nonFilteredFileExtensions>
			<!--不加这一行,xlsx文件会被过滤,然后在maven build的时候,去target下看对应的xlsx就是损坏的-->
			<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
		</nonFilteredFileExtensions>
	</configuration>            
</plugin>

解决:maven 构建时对该 excel 模板进行了过滤,导致文件损坏,解决办法,在过滤的时候把 xlsx 排除掉(<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>)。

相关推荐
Ledison718 小时前
Springboot 3.5.7 + Springcloud 2025 升级记录
java
没有bug.的程序员18 小时前
熔断、降级、限流:高可用架构的三道防线
java·网络·jvm·微服务·架构·熔断·服务注册
派大鑫wink18 小时前
【Day15】集合框架(三):Map 接口(HashMap 底层原理 + 实战)
java·开发语言
API技术员18 小时前
京东API接口:如何高效获取商品详情与SKU信息
python
派大鑫wink18 小时前
【Day14】集合框架(二):Set 接口(HashSet、TreeSet)去重与排序
java·开发语言
weixin_5150696618 小时前
BeanToMapUtil-对象转Map
java·工具类·java常用api
code_std19 小时前
保存文件到指定位置,读取/删除指定文件夹中文件
java·spring boot·后端
sort浅忆19 小时前
deeptest执行接口脚本,添加python脚本断言
开发语言·python
小许学java19 小时前
Spring事务和事务传播机制
java·数据库·spring·事务
大学生资源网19 小时前
基于Javaweb技术的宠物用品商城的设计与实现(源码+文档)
java·mysql·毕业设计·源码·springboot