前端excel下载功能excel文件在静态资源里前端用thymeleaf后端用spring boot
-
在静态资源文件夹中创建一个名为“excel”的文件夹,并将Excel文件放入其中。
-
在Thymeleaf模板中添加一个下载按钮,并将其链接到后端控制器的URL。例如:
<a href="/download/excel/example.xlsx">下载Excel文件</a>
- 在后端控制器中,使用Spring Boot的ResponseEntity来设置响应头和内容。例如:
@GetMapping("/download/excel/{filename:.+}")
public ResponseEntity<Resource> downloadExcel(@PathVariable String filename) throws IOException {
Resource resource = new ClassPathResource("static/excel/" + filename);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
这个控制器方法会根据文件名查找对应的Excel文件,并将其作为响应的内容返回。同时,它还设置了响应头,使得浏览器会提示用户下载文件。
- 在浏览器中点击下载按钮即可下载Excel文件
原文地址: https://www.cveoy.top/t/topic/fswC 著作权归作者所有。请勿转载和采集!