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

相关推荐
一只叫煤球的猫1 小时前
【🤣离谱整活】我写了一篇程序员掉进 Java 异世界的短篇小说
java·后端·程序员
斐波娜娜1 小时前
Maven详解
java·开发语言·maven
Bug退退退1231 小时前
RabbitMQ 高级特性之事务
java·分布式·spring·rabbitmq
程序员秘密基地1 小时前
基于html,css,vue,vscode,idea,,java,springboot,mysql数据库,在线旅游,景点管理系统
java·spring boot·mysql·spring·web3
皮皮林5511 小时前
自从用了CheckStyle插件,代码写的越来越规范了....
java
小码氓1 小时前
Java填充Word模板
java·开发语言·spring·word
会飞的天明1 小时前
Java 导出word 实现饼状图导出--可编辑数据
java·word
Muxiyale1 小时前
使用spring发送邮件,部署ECS服务器
java·服务器·spring
01传说2 小时前
vue3 配置安装 pnpm 报错 已解决
java·前端·vue.js·前端框架·npm·node.js
hunzi_13 小时前
搭建商城系统
java·uni-app·php