注意文件放置位置:resources跟目录下 !!!!
代码:
/**
* 下载***.xlsx模板
*/
@ApiOperation("下载***.xlsx模板")
@GetMapping("/downloadExcel")
public void downloadExcel(HttpServletResponse response) {
try {
//1、获取模板文件:使用ResourceUtils.getFile("classpath:")这样的方式,是获取不到路 径的(打成jar包部署后)
//File file = ResourceUtils.getFile("classpath:***.xlsx");
ClassPathResource resource = new ClassPathResource("***.xlsx");
//2、转换为文件流
InputStream inputStream = resource.getInputStream();
//3、指定默认下载名称
String fileName = resource.getFilename();
//4、配置response的头
response.reset();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
try {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//5、循环从文件中读出数据后写出,完成下载
byte[] b = new byte[1024];
int len;
while ((len = inputStream.read(b)) != -1) {
response.getOutputStream().write(b, 0, len);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
pom.xml
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.xlsx</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<!--打包的时候排除指定后缀文件,否则打包时会出现文件损坏的情况-->
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
</build>