前言:
Excel模板在你当前项目相对路径下,如下图所示
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/643ffdb76d6f4769a5793ccf65d41739.png)
代码如下:(为了直观,统一放在控制层)
java
/**
* 下载模板
* @param response
* @return
*/
@SneakyThrows
@GetMapping("/downloadTemplate")
public void downloadTemplate(HttpServletResponse response){
String fileName = "指标体系导入模板.xlsx";
ServletOutputStream out = response.getOutputStream();
try{
//文件在项目中的存放路径
String filePath = getClass().getResource("/static/" + fileName).getPath(); // 文件路径就是上图添的位置
filePath = URLDecoder.decode(filePath, "UTF-8");
//设置响应
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
FileInputStream inputStream = new FileInputStream(filePath);
int b = 0;
byte[] buffer = new byte[1024];
while ((b = inputStream.read(buffer)) != -1) {
// 写到输出流(out)中
out.write(buffer, 0, b);
}
inputStream.close();
}catch (Throwable e){
e.printStackTrace();
}finally{
try {
if (out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}