如何在spring中重用搜索结果生成exel报告

ncecgwcz  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(224)

我是spring的新手,我正在寻找最干净的方法来完成我正在尝试的工作:
我有一个控制器,它显示一个过滤的“搜索结果”页面,基于用户输入过滤参数的表单(在book实体中找到的fromdate和todate):

@GetMapping("/search_book")
public String searchBook(Book book, Model model, RedirectAttributes flash,
        @RequestParam(name = "page", defaultValue = "0") int page,
        @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date fromDate,
        @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date toDate) {

    Pageable pageable = PageRequest.of(page, 5);
    BookSpecification bookSpecification = new bookSpecification(book, fromDate, toDate);
    Page<Book> page = bookService.findAll(bookSpecification, pageable);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    PageRender<Book> pageRender = new PageRender<Book>(
            "/episode/search_book?fromDate=".concat(fromDate != null ? sdf.format(fromDate) : "")
                    .concat("&toDate=" + (toDate != null ? sdf.format(toDate) : "")),
            page);

    model.addAttribute("books", page);
    model.addAttribute("pageRender", pageRender);

    return "book/searchResults";
}

现在我需要一个“导出到excel”按钮在该页,以便用户可以将这些结果导出到excel表。
我可以做的是使用另一种方法再次执行查询和筛选,然后像这样构建excel(我仍然需要弄清楚如何获取这些筛选器):

@GetMapping("/export_excel")
    public void exportToExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setHeader("header", "some header value");

        // Build the bookSpecification and query the filtered results
        List<Book> books= bookService.findAll(bookSpecification);

        ExcelExporter excelExporter = new ExcelExporter(books);

        excelExporter.export(response);    
    }

但我想知道是否有一种方法可以只执行一次查询(当点击搜索按钮时),并在请求时(使用另一个按钮)在同一页面中提供excel下载。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题