Spring Boot & Thymeleaf 实现 Controller 层多个 Excel 下载
在 Controller 层的 action 中,可以通过 if 判断语句来实现多个 Excel 下载。前端使用 Thymeleaf 来渲染页面,后端使用 Spring Boot 来处理请求。
首先,定义一个 Controller 类,用来处理页面请求和下载文件的操作。在 Controller 中,定义一个 action 方法,例如 downloadExcel()。在这个方法中,使用 if 判断语句来判断用户需要下载的 Excel 文件,然后调用相应的下载方法。
例如,假设用户需要下载两个 Excel 文件,分别是 'file1.xlsx' 和 'file2.xlsx'。在 Controller 中,可以这样实现:
@Controller
public class ExcelController {
@Autowired
private ExcelService excelService;
@GetMapping(value = "/download")
public ResponseEntity<ByteArrayResource> downloadExcel(@RequestParam("file") String file) throws IOException {
byte[] data = null;
String filename = null;
if (file.equals("file1")) {
data = excelService.generateFile1();
filename = "file1.xlsx";
} else if (file.equals("file2")) {
data = excelService.generateFile2();
filename = "file2.xlsx";
}
// Set the content type and attachment header
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
headers.add("Content-Disposition", "attachment; filename=" + filename);
// Return the file as a ByteArrayResource
ByteArrayResource resource = new ByteArrayResource(data);
return ResponseEntity.ok()
.headers(headers)
.contentLength(data.length)
.body(resource);
}
}
在这个例子中,假设 ExcelService 类中有两个方法 generateFile1() 和 generateFile2(),用来生成 'file1.xlsx' 和 'file2.xlsx' 文件。在 downloadExcel() 方法中,使用 if 判断语句来判断用户需要下载哪个文件,然后调用相应的方法生成文件数据。最后,将文件数据打包成 ByteArrayResource 对象,设置 Content-Type 和 Content-Disposition 头,然后将文件作为响应返回给用户。
在前端页面中,使用 Thymeleaf 来渲染页面并发送下载请求。例如:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Download Excel</title>
</head>
<body>
<h1>Download Excel</h1>
<a th:href="@{/download(file='file1')}">Download File 1</a>
<a th:href="@{/download(file='file2')}">Download File 2</a>
</body>
</html>
在这个例子中,使用 Thymeleaf 来生成下载链接,例如 @{/download(file='file1')}。这个链接会发送 GET 请求到 /download 接口,并传递 file 参数。在 Controller 中,使用 @RequestParam 注解来接收 file 参数,并根据参数值来判断用户需要下载哪个文件。最后,将文件数据作为响应返回给用户,用户就可以直接下载 Excel 文件。
原文地址: https://www.cveoy.top/t/topic/oh0E 著作权归作者所有。请勿转载和采集!