在项目中通常会用到excel模板下载,但是在下载后却无法打开,下载代码如下:
public static void downloadTemplate(HttpServletResponse response, String fileName) {
try (InputStream fis = new ClassPathResource("/templates/" + fileName).getInputStream();
ServletOutputStream sos = response.getOutputStream()) {
// 设置响应头
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));
// 复制文件流
IOUtils.copy(fis, sos);
sos.flush();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("模板下载失败!");
}
}
下载后打开,显示错误!
需要在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配置文件里可以配置对项目进行统一编码,但是部分文件可能不需要进行重新编码,只需过滤掉不需要编码的文件类型即可。