简体   繁体   中英

Is there way to generate table with subtotal in Jasper Report?

Is there way to generate table with subtotal in Jasper Report?

I already get some reference for subtotal using querystring . I want to use subDataset and JRBeanCollectionDataSource . How can I do in template for subtotal?

template

<subDataset name="dataSource">
    <field name="product" class="java.lang.String"/>
    <field name="qty" class="java.lang.Integer"/>
    <field name="date" class="java.lang.Date"/>
</subDataset>
<parameter name="TableDataSource" class="net.sf.jasperreports.engine.JRDataSource"/>
....
<jr:table ...>
    <datasetRun subDataset="dataSource">
        <dataSourceExpression><![CDATA[$P{TableDataSource}]]></dataSourceExpression>
    </datasetRun>
    ......  
</jr:table>

program

list.add(new Product("AAA", 100, date));
list.add(new Product("AAA", 100, date));
list.add(new Product("AAA", 100, date));
list.add(new Product("BBB", 200, date));
list.add(new Product("BBB", 150, date));
list.add(new Product("BBB", 100, date));
new JRBeanCollectionDataSource(list));

Expected output

+--------+-----------+-------+
|Product |    Date   |  Qty  |
+--------+-----------+-------+
|AAA     | 08-08-210 | 100   |
|        | 08-09-210 | 100   |
|        | 08-10-210 | 100   |
+--------+-----------+-------|
|           SubTotal | 300   |
+--------+-----+-------------+
|BBB     | 08-08-210 | 200   |
|        | 08-09-210 | 150   |
|        | 08-10-210 | 100   |
+--------+-----------+-------|
|           SubTotal | 450   |
+--------+-----+-------------+

I think it's simple to calculate it out of the report and place in the DataSource

list.add(new Product("AAA", 100, date));
list.add(new Product("AAA", 100, date));
list.add(new Product("AAA", 100, date));
list.add(new Product("TOTAL:", 300, date)); //total AAA
list.add(new Product("BBB", 200, date));
list.add(new Product("BBB", 150, date));
list.add(new Product("BBB", 100, date));
list.add(new Product("TOTAL:", 450, date)); //total BBB
new JRBeanCollectionDataSource(list));

UPDATE: You can calculate the same on DB level

select 0 as ord, * from t
union all
select 1 as ord, 'Total' as product, sum(Qty) as Qty, null as date from t group by
order by ord, product

You can use report grouping. Here's what you should be doing.

  • Take a sub report move your data there.
  • Take a group which changes on product name ie AAA in sub report.
  • Take a variable that resets on group change and that calculates the sum Qty .

For more reference on report groups visit this link.

EDIT :

Alternatively you can use report scriplets to accomplish it. Visit here for more on report scriplets.

I suggest you use report scriplets this would save you from creating sub reports and report froups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM