使用来自两个存储库的信息来创建Excel电子表格

时间:2019-01-07 19:08:36

标签: java jxls

我想创建一个报告,将所有许可和保险从它们各自的存储库中提取到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();
        }
}

1 个答案:

答案 0 :(得分:1)

licenses and insurances are two separate lists that have programmatically nothing in common. The could be different in size, so that JXLS won't know at which row it should be used.

Therefore JXLS supports only a single Iterable in gridExport(). Your best bet is to join your lists together. It is up to you to decide whether to join them in the repository or a separate service (or hacked inside the controller), but it must definitely be a single collection.