work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

JasperReport 父子报表

Posted on 2021-06-14 19:30  work hard work smart  阅读(833)  评论(0编辑  收藏  举报

复杂报表或数据内容较多的时候,可以使用子报表解决。

 

1、制作父报表,主要有两种

1) 父报表中需要显示数据,使用子报表弥补sudio设计的不足。

2) 父报表不需要显示数据,只是作为子报表的载体,适用于复杂报表的设计。(接下来使用这种)

 

2、创建父报表

命名为: template5_parent.jrxml

 

 

在Basic Elements拖拽Subreport到Detail 1

 

 

选择template4_charts.jrxml,

 

 点击完成。

 

 

3、父报表传递数据

在template5_parent上创建Parameters

名称为sublist, 类型为java.util.List

 

 

4、子报表接收数据

 

 

在Value Class,点击右边的浏览

 

 

查找JRBeanCollectionDataSource

 

 

new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{sublist})

 

 

 sublist就是父报表定义的Parameters。

 

创建Parameters,命名为subpath

 

 

Expression填写$P{subpath}

 

 然后分表编译模板tempate4_chart.jrxml, template5_parent.jrxml. 

编译后拷贝到程序中。

 

 

5、Java代码编写

//父子报表
    @GetMapping("/jasper4_parent_child")
    public void jasper4_parent_child( HttpServletResponse response)
            throws Exception {
        List<StudentCount> studentList = new ArrayList<>();
        for (int i = 1; i <= 6; i++) {
            Random random = new Random();
            int count = ((Double) (random.nextDouble() * 10)).intValue();
            StudentCount s1 = new StudentCount();
            s1.setGrade("grade"+ i );
            s1.setNums(i * 20L + count);
            studentList.add(s1);
        }

        HashMap<String, Object> parameters = new HashMap<String, Object>();
        //子报表需要的数据
        parameters.put("sublist",studentList);
        //子报表路径
        Resource subResource = new ClassPathResource("templates/template4_charts.jasper");
        parameters.put("subpath",subResource.getFile().getPath());
        String templatePathParent = "templates/template5_parent.jasper";
        JasperReportUtil.exportToPdf(templatePathParent, parameters, studentList, response);
    }

  

 

6、效果图

访问: http://localhost:8080/jasper4_parent_child