首页 > 解决方案 > 使用来自两个存储库的信息创建 Excel 电子表格

问题描述

我想创建一个报告,将所有许可证和保险从各自的存储库中提取到 Excel 表中。有没有办法做到这一点:

@RequestMapping(value="/report/expirationReport")
public void getExpirationReport(Model model,HttpServletResponse response){
    List<License> licenses;
    List<Insurance> insurances;
    licenses = licenseRepository.findAll();
    insurances = insuranceRepository.findAll();

    List<String> headers=Arrays.asList("Legal Name","Principle Name","Type","State","Expiration");
    response.addHeader("Content-disposition", "attachment; filename=ExpirationReport.xls");
    response.setContentType("application/vnd.ms-excel");
    try {
        new SimpleExporter().gridExport(headers, licenses, insurances,"client.legalName, client.principleName,type,state,expiration", response.getOutputStream());
        response.flushBuffer();
    }catch (IOException e) {
        e.printStackTrace();
    }
}

两个存储库都已经存在,但我不能只添加保险(就像我上面所做的那样),因为 SimpleExporter 似乎只接受两个对象,然后是对象道具。知道如何让它接受所有三个对象吗?或者知道如何最好地将两个 repo findAll 函数结果连接/保存到一个数据对象中?

编辑:我可以通过查看客户表来完成这项工作,因为许可证和保险都有客户的外键。这是代码:

@RequestMapping(value="/report/expirationReport")
public void expirationReport(HttpServletResponse response){
    List<Client> clients=clientRepository.findAll();

        try {
            response.addHeader("Content-disposition", "attachment; filename=expirationReport.xlsx");
            response.setContentType("application/vnd.ms-excel");
            InputStream is= new ClassPathResource("static/reports/expirationReport.xlsx").getInputStream();
            Context context= new Context();
            context.putVar("clients", clients);

            JxlsHelper.getInstance().processTemplate(is,response.getOutputStream(),context);
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

标签: javajxls

解决方案


licenses并且insurances是两个单独的列表,它们在编程上没有共同点。大小可能不同,因此 JXLS 不知道应该在哪一行使用它。

因此 JXLS 仅支持单个Iterablein gridExport(). 您最好的选择是将您的列表加入到一起。由您决定是否将它们加入存储库或单独的服务(或在控制器内部被黑客入侵),但它绝对必须是单个集合。


推荐阅读