Tuesday, July 31, 2007

Custom sort of rows and columns without writing comparator

When doing JasperReports, I am often asked to sort the rows and columns in a particular ways other than alphabetical. JasperReports does support customized comparators for sorting. But I found it quite complicated to implement and not very easy to update in the future. Today I figured out a trick that can do arbitrary sorting easily.

In my sql statement, I concatenate the sequence number and the actually value together, for example, '01Banana', '02Orange', '03Apple'. Then in my report, I chop off the sequence number before displaying it, such as $F{field}.subString(2).

This trick works fine for small number of values.