Search code examples
headerjasper-reportsexport-to-excel

How to set excel header font and style in print preview?


I'm using iReport 5.6.0 for creating a report, I want to add a header for excel when print preview, I tried adding this line in the jrxml

<property name="net.sf.jasperreports.export.xls.sheet.header.left" value="My Left Text"/>
<property name="net.sf.jasperreports.export.xls.sheet.header.center" value="My Center Text"/>
<property name="net.sf.jasperreports.export.xls.sheet.header.right" value="My Right Text"/>

This is working fine, but the problem is I don't know how to add font style or font size.

Is there a way that I can add font style, font size, or font color?


Solution

  • Jasper report has no attribute in which you can specify the font used for header.

    but we can do some crazy stuff

    Jasper report is using Apache POI to export to excel, in POI to set the page header, commands like this is used (see HSSFHeader)

    header.setCenter(HSSFHeader.font("Calibri", "bold") + HSSFHeader.fontSize((short) 16) + "My Center Text");
    

    This is actually generating a String that is set to center.

    &"Calibri,bold"&16My Center Text
    

    Since we need to put it in an xml attribute we need to escape " with &quot; and & with &amp;.

    <property name="net.sf.jasperreports.export.xls.sheet.header.center" 
             value="&amp;&quot;Calibri,bold&quot;&amp;16My Center Text"/>
    

    Voilà

    Result

    To understand how the String should be when switching from different style and using other POI attributes, an easiest way is to make a small java program, for example

    System.out.println(HSSFHeader.font("Times New Roman", "regular") + 
             HSSFHeader.fontSize((short) 12) + "My " + HSSFHeader.startBold() + "Bold" + 
             HSSFHeader.endBold() + " Text with date " + HSSFHeader.date());
    

    &"Times New Roman,regular"&12My &BBold&B Text with date &D

    just escape and insert into to value attribute