在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文件

controller层一个action控制多个excel下载用if判断语句如何实现前端用thyme leaf后端用spring boot

原文地址: https://www.cveoy.top/t/topic/ftHz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录