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>)。

相关推荐
Stara05111 小时前
基于多头自注意力机制(MHSA)增强的YOLOv11主干网络—面向高精度目标检测的结构创新与性能优化
人工智能·python·深度学习·神经网络·目标检测·计算机视觉·yolov11
Java致死1 小时前
设计模式Java
java·开发语言·设计模式
源码方舟1 小时前
SpringBoot + Shiro + JWT 实现认证与授权完整方案实现
java·spring boot·后端
那雨倾城2 小时前
使用 OpenCV 将图像中标记特定颜色区域
人工智能·python·opencv·计算机视觉·视觉检测
2401_cf4 小时前
为什么hadoop不用Java的序列化?
java·hadoop·eclipse
帮帮志4 小时前
idea整合maven环境配置
java·maven·intellij-idea
LuckyTHP4 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
热河暖男4 小时前
【实战解决方案】Spring Boot+Redisson构建高并发Excel导出服务,彻底解决系统阻塞难题
spring boot·后端·excel
mahuifa6 小时前
(7)python开发经验
python·qt·pyside6·开发经验
无声旅者7 小时前
深度解析 IDEA 集成 Continue 插件:提升开发效率的全流程指南
java·ide·ai·intellij-idea·ai编程·continue·openapi