Column header missing from Excel and PDF export using JasperDesign class

Hi there,

I am using JasperDesign class. I am using the code from here. In the tutorial, they are using Java Beans and I am passing map as datasource.

Here is the code:

import java.util.Arrays;
 
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.design.*;
import net.sf.jasperreports.engine.type.HorizontalTextAlignEnum;
 
/**
 * Uses the Jasper Report API to dynamically add columns to the Report
 */
public class DynamicReportBuilder {
//The prefix used in defining the field name that is later used by the JasperFillManager
 
//    public static final String COL_EXPR_PREFIX = "col";
    // The prefix used in defining the column header name that is later used by
    //    the JasperFillManager
 
//    public static final String COL_HEADER_EXPR_PREFIX = "header";
    // The page width for a page in portrait mode with 10 pixel margins
    private final static int TOTAL_PAGE_WIDTH = 545;
    // The whitespace between columns in pixels
    private final static int SPACE_BETWEEN_COLS = 5;
    // The height in pixels of an element in a row and column
    private final static int COLUMN_HEIGHT = 12;
    // The total height of the column header or detail band
    private final static int BAND_HEIGHT = 15;
    // The left and right margin in pixels
    private final static int MARGIN = 10;
    // The JasperDesign object is the internal representation of a report
    private JasperDesign jasperDesign;
    // The number of columns that are to be displayed
    private int numColumns;
 
    private String [] columnHeaders = new String[numColumns];
 
    public DynamicReportBuilder(JasperDesign jasperDesign, int numColumns, String[] columnHeaders) {
        this.jasperDesign = jasperDesign;
        this.numColumns = numColumns;
        this.columnHeaders = columnHeaders;
    }
 
    public void addDynamicColumns() throws JRException {
        JRDesignBand detailBand = new JRDesignBand();
        JRDesignBand headerBand = new JRDesignBand();
        JRDesignStyle normalStyle = getNormalStyle();
        JRDesignStyle columnHeaderStyle = getColumnHeaderStyle();
        jasperDesign.addStyle(normalStyle);
        jasperDesign.addStyle(columnHeaderStyle);
        int xPos = MARGIN;
        int columnWidth = (TOTAL_PAGE_WIDTH - (SPACE_BETWEEN_COLS * (numColumns - 1))) / numColumns;
        HorizontalTextAlignEnum horizontalAlignment = null;
 
 
        System.out.println("in addDynamicColumns || columnheaders= "+Arrays.toString(columnHeaders));
 
        for (int i = 0; i < numColumns; i++) {
 
            // Create a Column Field
 
            JRDesignField field = new JRDesignField();
            field.setName(columnHeaders[i]);
            field.setValueClass(java.lang.String.class);
            jasperDesign.addField(field);
 
            // Create a Header Field
 
            JRDesignField headerField = new JRDesignField();
            headerField.setName("test"+i);
            headerField.setValueClass(java.lang.String.class);
            jasperDesign.addField(headerField);
 
            // Add a Header Field to the headerBand
 
            headerBand.setHeight(BAND_HEIGHT);
            JRDesignTextField colHeaderField = new JRDesignTextField();
            colHeaderField.setX(xPos);
            colHeaderField.setY(2);
            colHeaderField.setWidth(columnWidth);
            colHeaderField.setHeight(COLUMN_HEIGHT);
            colHeaderField.setBold(true);
            colHeaderField.setHorizontalTextAlign(horizontalAlignment.LEFT);
            colHeaderField.setStyle(columnHeaderStyle);
            JRDesignExpression headerExpression = new JRDesignExpression();
 
            headerExpression.setValueClass(java.lang.String.class);
 
            headerExpression.setText("$F{" + columnHeaders[i] + "}");
            colHeaderField.setExpression(headerExpression);
            headerBand.addElement(colHeaderField);
            // Add text field to the detailBand
            detailBand.setHeight(BAND_HEIGHT);
            JRDesignTextField textField = new JRDesignTextField();
            textField.setX(xPos);
            textField.setY(2);
            textField.setWidth(columnWidth);
            textField.setHeight(COLUMN_HEIGHT);
            textField.setHorizontalTextAlign(horizontalAlignment.LEFT);
            textField.setStyle(normalStyle);
            JRDesignExpression expression = new JRDesignExpression();
            expression.setValueClass(java.lang.String.class);
            expression.setText("$F{" + columnHeaders[i]+ "}");
            textField.setExpression(expression);
            detailBand.addElement(textField);
            xPos = xPos + columnWidth + SPACE_BETWEEN_COLS;
        }
        jasperDesign.setColumnHeader(headerBand);
        ((JRDesignSection) jasperDesign.getDetailSection()).addBand(detailBand);
    }
 
    private JRDesignStyle getNormalStyle() {
        JRDesignStyle normalStyle = new JRDesignStyle();
        normalStyle.setName("Sans_Normal");
        normalStyle.setDefault(true);
        normalStyle.setFontName("SansSerif");
        normalStyle.setFontSize((float) 8);
        normalStyle.setPdfFontName("Helvetica");
        normalStyle.setPdfEncoding("Cp1252");
        normalStyle.setPdfEmbedded(false);
        return normalStyle;
    }
 
    private JRDesignStyle getColumnHeaderStyle() {
        JRDesignStyle columnHeaderStyle = new JRDesignStyle();
        columnHeaderStyle.setName("Sans_Header");
        columnHeaderStyle.setDefault(false);
        columnHeaderStyle.setFontName("SansSerif");
        columnHeaderStyle.setFontSize((float) 10);
        columnHeaderStyle.setBold(true);
        columnHeaderStyle.setPdfFontName("Helvetica");
        columnHeaderStyle.setPdfEncoding("Cp1252");
        columnHeaderStyle.setPdfEmbedded(false);
        return columnHeaderStyle;
    }
}

The controller that calls the above code:

@RequestMapping (value = "/dynamicExport/{exportType}",  method = RequestMethod.POST)
    public void dynamicExport(Model model, HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> formData,
            @PathVariable("exportType") String exportType) throws JRException, IOException  {
 
        try {
 
 
            String [] columnHeaders  = formData.get("headers").split(",");
            String [] data = formData.get("csvData").split("\n");
 
            Collection<Map<String, ?>> reportRows = new ArrayList();            
 
            for(int i=0; i<data.length; i++) {
 
                HashMap<String, String> rowMap = new HashMap<String, String>();
 
                String [] row = data[i].split("\",\"");
 
 
 
                for(int j=0; j<columnHeaders.length; j++) {
 
                    String value = row[j].replace("\"", "");
 
                    rowMap.put(columnHeaders[j], value);
                }
 
                reportRows.add(rowMap);
            }
 
            System.out.println("exportType= "+exportType);
 
            InputStream is = getClass().getResourceAsStream("/dynamic.jrxml");
            JasperDesign jasperReportDesign = JRXmlLoader.load(is);
            DynamicReportBuilder reportBuilder = new DynamicReportBuilder(jasperReportDesign, columnHeaders.length, columnHeaders);
            reportBuilder.addDynamicColumns();
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperReportDesign);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("REPORT_TITLE", "Sample Dynamic Columns Report");
 
            JRMapCollectionDataSource dataSource = new JRMapCollectionDataSource(reportRows);
 
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
 
            if(exportType.equalsIgnoreCase("pdf"))
            {
                JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
                response.setContentType("application/pdf");
                response.addHeader("Content-Disposition", "inline; filename=jasperReport.pdf;");
            }
 
            else if(exportType.equalsIgnoreCase("excel"))
            {
 
                JRXlsxExporter exporter = new JRXlsxExporter();
                exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
                File outputFile = new File("excelTest.xlsx");
                exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputFile));
                exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
                SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration(); 
                configuration.setOnePagePerSheet(false); // setup configuration
                exporter.setConfiguration(configuration);
                response.setHeader("Content-Disposition", "attachment;filename=jasperReport.xlsx");
                response.setContentType("application/octet-stream");
                exporter.exportReport();                
            }
 
 
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
 
 
 
    }

I am able to view the data but the column headers are missing, So far I have tried only Excel and PDF export.

I am not able to figure out what am I missing.

jagrutit's picture
Joined: Jul 31 2022 - 10:10pm
Last seen: 7 months 5 days ago

0 Answers:

No answers yet
Feedback
randomness