SpringBoot下载Excel文件无法打开
在项目中通常会用到excel模板下载,但是在下载后却无法打开,下载代码如下:
@GetMapping("/test") public void test(HttpServletResponse response) throws IOException { String fileName = "学生信息导入模板.xlsx"; InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/" + fileName); response.setHeader("Access-Control-Expose-Headers", "content-disposition"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream"); response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); int len = 0; byte bytes[] = new byte[1024]; OutputStream out = response.getOutputStream(); while ((len = in.read(bytes)) > 0) { out.write(bytes, 0, len); } in.close(); out.close(); }
文件存放位置:
下载后打开,显示错误
在pom中添加以下代码即可解决。
<plugin> <groupId>org.apache.maven.plugins</groupId> <version>2.6</version> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>UTF-8</encoding> <nonFilteredFileExtensions> <nonFilteredFileExtension>xlsx</nonFilteredFileExtension> </nonFilteredFileExtensions> </configuration> </plugin>
主要原因是maven在打包项目的时候pom.xml配置文件里可以配置对项目进行统一编码,但是部分文件可能不需要进行重新编码,只需过滤掉不需要编码的文件类型即可。
就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !
推荐这些文章:
Springboot 读取 resource 目录下的Excel文件并下载
如果 inputStream 为null ,或者提示 文件路径不存在,执行 mvn clean 并 重启项目,查看target 目录下是否存在该文件
@GetMapping("/download")
public void download(HttpServletResponse response) {
...
1. 背景
经常遇到excel类型的数据,需要转为utf8编码的txt文本,以便入库hive。excel文件的编码格式是 GBK
2. GBK转为utf8
# 首先将excel另存为csv
# 将csv文件编码格式转换
iconv -f gbk -t utf-8 file1.csv -o file2.txt
# 参数解释
-f enc...
项目内的文件,如zip压缩包经过Maven编译到target后文件破损怎么办
在POM文件的Maven插件修改
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <v...
java.util.zip.ZipException: invalid stored block lengths 导出excel遇到的异常
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.1.0</vers...
解决:Plugin 'org.apache.maven.plugins:maven-resources-plugin:' not found
加入下面的配置就可以了
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</art...
在pom文件中的build里面添加
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin<...
需求
为了便于功能模块之间的解耦合,需要将不同功能的代码放在不同的目录。
处理
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plu...
【Maven/Cli】如何解决错误:Cannot resolve plugin org.springframework.boot:spring-boot-maven-plugin:<unknown>
这个问题是在我制作一个SpringCLI程序的初期出现的,因此定位比较容易,出现这样的问题是因为我在pom里加入了如下节点:
<build>
<plugins>
<plugin>
<groupId>org.s...
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId&...
Could not initialize class org.apache.maven.plugin.war.util.WebappStructureSerializer
在pom.xml中添加,更加插件
<build><finalName>itrip-search</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><arti...
文章链接:https://www.dianjilingqu.com/4149.html
本文章来源于网络,版权归原作者所有,如果本站文章侵犯了您的权益,请联系我们删除,联系邮箱:saisai#email.cn,感谢支持理解。