Search code examples
javaapache-poijasper-reportsexport-to-excelods

How to generate both xlxs and ods - Java


I'm building an application with spring-boot and Java 11 that has a requirement that asks to export a report in ods and xlsx.

I read that jasper reports can support this. But there's no documentation that actually says that might be possible.

I also thought of creating an implementation of a TemplateClass and implementing an xlsx exporter with apache poi and implementing an ods exporter with another lib.

Do you know a better way?


Solution

  • This got me so far, with output to a Servlet OutputStream, but the files where often corrupt. Ods has built in support in recent Jasper e.g. I tried this in 6.18.1.

    if (format.equals("xlsx")) {
            JRXlsxExporter exporter = new JRXlsxExporter(); // initialize exporter
            exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); // set compiled r
            SimpleXlsxReportConfiguration reportConfigXLS = new SimpleXlsxReportConfiguration();
            Map<String, String> dateFormats = new HashMap<String, String>();
            dateFormats.put("EEEEE dd MMMMM yyyy", "ddd, mmm d, yyyy");
            reportConfigXLS.setFormatPatternsMap(dateFormats);
            reportConfigXLS.setIgnoreGraphics(true);
            reportConfigXLS.setOnePagePerSheet(true); // setup configuration
            reportConfigXLS.setDetectCellType(true);
            reportConfigXLS.setSheetNames(new String[]{"Active Patients"});
            exporter.setConfiguration(reportConfigXLS);
            exporter.setExporterOutput(new 
              SimpleOutputStreamExporterOutput(out));
            exporter.exportReport();
    } else if (format.equals("ods")) {
            JROdsExporter exporter = new JROdsExporter(); // initialize exporter
            exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); // set compiled r
            SimpleOdsExporterConfiguration reportConfigXLS = new SimpleOdsExporterConfiguration();
            exporter.setConfiguration(reportConfigXLS);
            exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(out));
            exporter.exportReport();
    }
    byte[] binData = out.toByteArray();
    OutputStream out1 = response.getOutputStream();
    out1.write(binData);
    out1.close();
    response.setContentLength(binData.length);