Can JasperReports produce Excel file with column w

2019-02-19 22:41发布

问题:

When JasperReports outputs a file in the Excel xls format, the columns when viewed are only the fixed width determined in the jasper XML.

This is a problem when the data in the columns is of varying widths, causing some columns to wrap.

I've had a look at the API and the DTD and there doesn't seem to be a way of setting the column widths to auto adjust.

i.e.instead of displaying as

  emailAdress
  @email.com

display as

  emailAdress@email.com

Is it possible to do this at all?

This question is similar to Jasper report column width

回答1:

We can achieve the effect of auto column's width with help of net.sf.jasperreports.export.xls.auto.fit.column property. If we set the value as true the auto width will be enabled. The default value of this property is false.

The working sample

We can use the csv datasource and simple report designed in Jaspersoft Studio to check the result.

The report's design will be simple - only one textField in Detail band.

Datasource

It is very simple - only one column email. The first row contains just a column's name. We can told the datasource adapter to skip this first line.

email
emailAdress@email.com
short@have.org
a@b.net

Report's template

The width of textField will be too small to show the full text.

To "turn on" the auto width we should set the net.sf.jasperreports.export.xls.auto.fit.column property.

The jrxml will be:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="test_auto_width_excel" pageWidth="100" pageHeight="842" columnWidth="100" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="c899fa54-7405-4371-b34f-429f5959b593">
    <queryString language="csv">
        <![CDATA[]]>
    </queryString>
    <field name="email" class="java.lang.String"/>
    <detail>
        <band height="30" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="30" uuid="04d0735d-a1b6-4a8f-b252-b8772d7c5abd">
                    <property name="net.sf.jasperreports.export.xls.auto.fit.column" value="true"/>
                </reportElement>
                <textFieldExpression><![CDATA[$F{email}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

Output result

The generated xls file without using property looks like this (opened in MS Excel):

The generated xls file with net.sf.jasperreports.export.xls.auto.fit.column property looks like this (opened in MS Excel):


Notes

  • In both cases the xls files were generated in Jaspersoft Studio.
  • The Advanced Excel Features article contains more information about tricks of exporting report to MS Excel format