Jorge
Jorge

Reputation: 291

How to force crosstab to ignore width with Java code?

This method below export me a report to xlsx (excel) using JasperReport, but i have a problem. I need to set the property (ignore width == true), i need to set on java because i have another method that export me to PDF. I have tried so many forms but no luck. Any suggestion?

The property i need is called "Property_ignore_width", i need to know how to set this property on java.

public void exportexcel() throws JRException, IOException {
        conexion con = new conexion();
        Map<String, Object> parametros = new HashMap<String, Object>();
        FacesContext context = FacesContext.getCurrentInstance();
        ServletContext servleContext = (ServletContext) context.getExternalContext().getContext();
        parametros.put("RutaImagen", servleContext.getRealPath("/reportes/"));
        parametros.put("movimiento", movimiento);
        parametros.put("desde", desde);
        parametros.put("hasta", hasta);

        String reporte = movimiento.equals("Descarga") ? "GeneralNaves.jasper" : "GeneralNavesExport.jasper";

        String dirReporte = servleContext.getRealPath("/reportes/" + reporte);
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.addHeader("Content-disposition", "attachment;filename=ReporteNaves_A_Naves.xlsx");
        response.setContentType("application/xlsx");

        JasperPrint impres = JasperFillManager.fillReport(dirReporte, parametros, con.getConnection());
        JRXlsxExporter expor = new JRXlsxExporter();
        expor.setExporterInput(new SimpleExporterInput(impres));
        expor.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));

        SimpleXlsxReportConfiguration config = new SimpleXlsxReportConfiguration();
        config.setCollapseRowSpan(Boolean.FALSE);
        config.setWhitePageBackground(Boolean.FALSE);
        config.setRemoveEmptySpaceBetweenRows(Boolean.TRUE);
        expor.setConfiguration(config);
        expor.exportReport();
        context.responseComplete();
    }

Upvotes: 2

Views: 1076

Answers (1)

Alex K
Alex K

Reputation: 22857

We can change the value of net.sf.jasperreports.crosstab.ignore.width property with help of JasperReports API.

This property should be set for Crosstab element, not for the whole report. It means that we should get the Crosstab element and use its method JRCrosstab.setIgnoreWidth(boolean)

Example

We can use the simple template with crosstab at Summary band with csv datasource.

Datasource

The csv datasource is using in example.

language,framework
Java,Guava
Java,Lombok
Java,JasperReports
Java,Spring
Java,Vaadin
C#,ASP.NET MVC
C#,NancyFX
C#,Automapper
JavaScript,AngularJS
JavaScript,React
JavaScript,jQuery

The name of data adapter for this datasource in the example below is frameworks.csv. The first line from the file is skipped - it is contains the column's name.

Report template

The Crosstab is using the main dataset.

<?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="Crosstab with dynamic width" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="731dbfe4-e4ef-4631-8a59-1952b5bf048c">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="frameworks.csv"/>
    <field name="language" class="java.lang.String"/>
    <field name="framework" class="java.lang.String"/>
    <summary>
        <band height="120">
            <crosstab ignoreWidth="false">
                <reportElement x="90" y="30" width="200" height="90" uuid="8cc82b0a-4e26-4cc6-b0e2-e5d13a5190df">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                </reportElement>
                <rowGroup name="language" width="60" totalPosition="End">
                    <bucket class="java.lang.String">
                        <bucketExpression><![CDATA[$F{language}]]></bucketExpression>
                    </bucket>
                    <crosstabRowHeader>
                        <cellContents mode="Opaque">
                            <textField>
                                <reportElement x="0" y="0" width="60" height="20" uuid="449ab423-ade7-4962-804c-dc39f326eaa6"/>
                                <textFieldExpression><![CDATA[$V{language}]]></textFieldExpression>
                            </textField>
                        </cellContents>
                    </crosstabRowHeader>
                    <crosstabTotalRowHeader>
                        <cellContents mode="Opaque">
                            <staticText>
                                <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="f3873d23-8f90-46ec-8e4a-7ea5635eb3aa"/>
                                <text><![CDATA[Total language]]></text>
                            </staticText>
                        </cellContents>
                    </crosstabTotalRowHeader>
                </rowGroup>
                <columnGroup name="framework" height="20" totalPosition="End">
                    <bucket class="java.lang.String">
                        <bucketExpression><![CDATA[$F{framework}]]></bucketExpression>
                    </bucket>
                    <crosstabColumnHeader>
                        <cellContents mode="Opaque">
                            <textField>
                                <reportElement x="0" y="0" width="60" height="20" uuid="4ec3e655-ea93-406a-b5b9-b56a46c12b19"/>
                                <textFieldExpression><![CDATA[$V{framework}]]></textFieldExpression>
                            </textField>
                        </cellContents>
                    </crosstabColumnHeader>
                    <crosstabTotalColumnHeader>
                        <cellContents mode="Opaque">
                            <staticText>
                                <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="4f9b4bdc-24fb-4df9-ab5f-423c82939535"/>
                                <text><![CDATA[Total framework]]></text>
                            </staticText>
                        </cellContents>
                    </crosstabTotalColumnHeader>
                </columnGroup>
                <measure name="language_MEASURE" class="java.lang.Integer" calculation="Count">
                    <measureExpression><![CDATA[$F{language}]]></measureExpression>
                </measure>
                <crosstabCell width="60" height="20">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" uuid="5e9cc753-3f32-4ab8-b79d-073fc574c85f"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" columnTotalGroup="framework">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="1ec48067-6435-463e-9688-768be0dd33be"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" rowTotalGroup="language">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="4208c8c9-fffa-48c3-acaa-6aeccc72c141"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" rowTotalGroup="language" columnTotalGroup="framework">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="efb32f08-a362-4b68-b9ed-ba36a944d385"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
            </crosstab>
        </band>
    </summary>
</jasperReport>

At Jaspersoft Studio the report's design looks like: Report's design at JSS

Java code

The main idea is to get crosstab element at Summary band and modify its property.

The Java 8 based code for setting property:

JasperReport jasperReport;
try (InputStream inputStream = JRLoader.getResourceInputStream(report.getTemplateName())) {
    jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream));
    Arrays.stream(jasperReport.getSummary().getElements()).filter(element -> element instanceof JRCrosstab)
            .forEach(jrElement -> ((JRCrosstab) jrElement).setIgnoreWidth(true)); // get all crosstabs and set PROPERTY_IGNORE_WIDTH property
}

try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("frameworks.csv")) {
    Map<String, Object> params = new HashMap<>();
    JRCsvDataSource ds = new JRCsvDataSource(inputStream);
    ds.setUseFirstRowAsHeader(true);

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, ds);

    exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    SimpleOutputStreamExporterOutput exporterOutput = null;
    try {
        exporterOutput = new SimpleOutputStreamExporterOutput(file);
        exporter.setExporterOutput(exporterOutput);
        exporter.exportReport();
    } finally {
        if (exporterOutput != null) {
            exporterOutput.close();
        }
    }
}

Output result

The result generated by code will be: The output pdf file

If we commented string of code with setIgnoreWidth calling (net.sf.jasperreports.crosstab.ignore.width == false) the result will be:

The output pdf file. Ignore width = false

Upvotes: 2

Related Questions