Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasper Reports crosstab sorting with comparatorExpression

I'm trying to sort my dynamic columns in a cross tab according to some custom scheme.

In the docs I found mention of comparatorExpression: Crosstab group bucket comparator expression. The result of this expression is used to sort the buckets, in ascending or descending order. If no comparator expression is specified, the natural order will be used.

but I don't understand what the expression should look like. Can I somehow use a regular java comparator? Can someone share an example?

like image 437
JayL Avatar asked Feb 22 '10 22:02

JayL


1 Answers

I've had the same issue and did not find any examples or explanation but I found how to do it. I'll explain, so hopefully other people can use this solution.

I've used the code below for jasperreports 3.1.0 and iReport 3.1.4, but I guess it works for pretty much all versions.

First you'll have to make sure that you know wich class you have in the bucket expression for your row/column group. By default this is java.lang.String, but I have a custom class there. For this to work I needed to edit the xml like this for my column group:

<bucketExpression class="java.lang.String"><![CDATA[$F{customObj}]]></bucketExpression>

to

<bucketExpression class="com.project.CustomObj"><![CDATA[$F{customObj}]]></bucketExpression>

Obviously this customObj value is a field with the corresponding class, defined in the report itself.

Then you'll need to add a Comparator as a parameter, for example:

parameters.put("OVERRIDE_Comparator", new Comparator<CustomObj>() {
    public int compare(CustomObj c1, CustomObj c2) {
        //create your custom compare logic over here, this code works as if no custom Comparator is used
        return c1.compareTo(c2);
    }
});

Now add such a OVERRIDE_Comparator parameter in the jasperreport, using the java.util.Comparator Parameter Class.

Final step: Put $P{OVERRIDE_Comparator} as the Comparator Expression in the row/column group you needed.

When compiling such a report, the most likely compile error would be casting issues. Jasperreports defaults to java.lang.String, you might need to edit the xml of the report manually to get the correct class at each step.

(I found out this method from some asian site, thankfully the code itself was readable! :-) )

like image 191
Pieter VN Avatar answered Sep 22 '22 22:09

Pieter VN