JasperReports export to Excel uses only last set background color

2020-02-26 java jasper-reports export-to-excel

Im pretty pretty new to Dynamic-Jasper, but due to work i had to add a new feature to our already implemented solution.

My Problem

The Goal is to add a Column to a report that consists only out of a background-color based on some Information. I managed to do that, but while testing I stumbled upon a Problem. While all my Columns in the html and pdf view had the right color, the Excel one only colored the fields in the last Color.

While debugging i noticed, that the same colored Fields had the same templateId, but while all Views run through mostly the same Code the Excel one showed different behavior and had the same ID in all fields.

My Code where I manipulate the template

for(JRPrintElement elemt : jasperPrint.getPages().get(0).getElements()) {
         if(elemt instanceof JRTemplatePrintText) {
                   JRTemplatePrintText text = (JRTemplatePrintText) elemt;
                   (...)
                   if (text.getFullText().startsWith("COLOR_IDENTIFIER")) {
                            String marker = text.getFullText().substring(text.getFullText().indexOf('#') + 1);
                            text.setText("ID = " + ((JRTemplatePrintText) elemt).getTemplate().getId());
                            int rgb = TypeConverter.string2int(Integer.parseInt(marker, 16) + "", 0);
                            ((JRTemplatePrintText) elemt).getTemplate().setBackcolor(new Color(rgb));
                   }
         }
}

The html view

The Excel view

Temporary Conclusion

The same styles uses the same Objects in the background and the JR-Excel export messes something up by assigning the same Object to all the Fields that I manipulated there. If anyone knows of a misstake by me or potential Solutions to change something different to result the same thing please let me know.

Something different I tried earlier, was trying to set the field in an evaluate Method that was called by Jasper. In that method we assign the textvalue of each field. It contained a map with JRFillFields, but unfortunatelly the Map-Implementation denied access to them and just retuned the Value of those. The map was provided by dj and couldn't be switched with a different one.

Edit

We are using JasperReports 6.7.1

Answers

I found a Solution, where I replaced each template with a new one that was supposed to look exactly alike. That way every Field has its own ID guaranteed and its not up to chance, how JasperReports handles its Data internaly.

JRTemplateElement custom = 
   new JRTemplateText(((JRTemplatePrintText) elemt).getTemplate().getOrigin(), 
   ((JRTemplatePrintText) elemt).getTemplate().getDefaultStyleProvider());
custom.setBackcolor(new Color(rgb));
custom.setStyle(((JRTemplatePrintText) elemt).getTemplate().getStyle());
((JRTemplatePrintText) elemt).setTemplate(custom);

Related