Almost every business application I worked on needed “reports” sooner or later. The word hides two different things, and most of the trouble I have seen came from treating them as one:
- Documents: an invoice, a delivery note, a monthly statement. Fixed layout, printed or sent as PDF, usually a few pages. The look matters. People compare it with the paper version.
- Data exports: “give me all orders of last year in Excel”. Many rows, simple layout, the user filters and pivots it afterwards. Size and correct cell types matter, the look does not.
For the first kind I use JasperReports. For the second kind I use Apache POI with SXSSF, or EasyExcel. I would not build a 200,000-row export with JasperReports, and I would not build an invoice with POI.
Versions in this post, as of late October 2024: JasperReports 7.0.1 and 6.21.4, Apache POI 5.3.0, EasyExcel 4.0.3, Spring Boot 3.3.
PDF documents with JasperReports
Template, compile, fill, export
You design the layout in Jaspersoft Studio. It saves a .jrxml file (XML). At runtime there are three steps:
- Compile the
.jrxmlinto aJasperReportobject (or a.jasperfile). - Fill it with parameters and a data source. The result is a
JasperPrint, the finished pages in memory. - Export the
JasperPrintto PDF (or another format).
@Service
public class InvoiceReport {
private final JasperReport template;
public InvoiceReport() throws JRException, IOException {
try (InputStream in = new ClassPathResource("reports/invoice.jrxml").getInputStream()) {
this.template = JasperCompileManager.compileReport(in); // once, at startup
}
}
public void writePdf(Invoice invoice, OutputStream out) throws JRException {
Map<String, Object> params = new HashMap<>();
params.put("invoiceNo", invoice.number());
params.put("customerName", invoice.customerName());
params.put(JRParameter.REPORT_LOCALE, Locale.GERMANY);
JRDataSource lines = new JRBeanCollectionDataSource(invoice.lines());
JasperPrint print = JasperFillManager.fillReport(template, params, lines);
JasperExportManager.exportReportToPdfStream(print, out);
}
}
Compiling is slow, so do it once and keep the JasperReport. A compiled report can be shared between
threads; filling creates new objects each time. I have seen code that compiles the template on every
request. It works in development and gets slow under load.
JRBeanCollectionDataSource reads the report fields from JavaBean getters, so I use small classes with
getters for report rows. A list in memory is fine here. The report is a document, so the data is small.
JasperReports 7 is a breaking release
JasperReports 7.0.0 came out in June 2024 and 7.0.1 in early October. Things to know before you upgrade:
- The library is split into several jars. PDF export is now in
jasperreports-pdf(it uses OpenPDF), and the default DejaVu fonts are injasperreports-fonts. With only the core jar, the PDF exporter class is missing at runtime. The exporter class also moved to the packagenet.sf.jasperreports.pdf. - The JRXML format changed. The project says JRXML files from version 6 or older cannot be loaded by
version 7 alone; they must be converted with Jaspersoft Studio 7. Compiled
.jasperfiles must also be recompiled. - Deprecated code was removed.
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>7.0.1</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-pdf</artifactId>
<version>7.0.1</version>
</dependency>
The 6.x line still gets releases (6.21.4 this month). For a project with many existing templates, I stay on 6.21.x for now and plan the move to 7 as its own task, with all templates converted in one go. Keep the Studio version and the library version on the same major version, or you will fight file format errors.
CJK fonts: the pitfall everybody hits
The PDF export does not use the operating system fonts the way you might expect. If a text field uses a font that the PDF exporter cannot find, you get one of these:
- An error about a missing font, because
net.sf.jasperreports.awt.ignore.missing.fontisfalseby default. This is good, it fails early. - Empty spaces where Chinese, Japanese or Korean characters should be. This happens when the font used for PDF (the default PDF font is Helvetica) has no glyphs for these characters. It often looks fine in the Studio preview, because the preview renders with Java AWT, which can use system fonts.
The reliable fix is a font extension: a jar that contains the TTF files and an XML file that maps a font family name to them, with embedding turned on. Jaspersoft Studio can export installed fonts as such a jar. The XML looks like this (this is the format of the DejaVu fonts that ship with JasperReports):
<fontFamilies>
<fontFamily name="Noto Sans SC">
<normal>fonts/NotoSansSC-Regular.ttf</normal>
<bold>fonts/NotoSansSC-Bold.ttf</bold>
<pdfEncoding>Identity-H</pdfEncoding>
<pdfEmbedded>true</pdfEmbedded>
</fontFamily>
</fontFamilies>
Then use exactly this family name in the template. Points I learned the hard way:
Identity-His needed for CJK text. Embedding is needed so the PDF looks the same on a machine without the font.- I use plain TTF files, one file per style, like the DejaVu extension that ships with JasperReports.
Font collection files (
.ttc) are a common source of trouble, so I pick a TTF download of the font. - Check the font licence before you put it in a jar and ship it. Fonts like Noto are under the SIL Open Font License, which allows embedding.
- CJK fonts are big. The PDF exporter embeds only the used glyphs, but the jar itself can add many megabytes to the application.
- Test in the Docker image you deploy, not only on your laptop. Slim base images have almost no fonts.
Memory for big documents
JasperPrint keeps all pages in memory. For a 20-page invoice this does not matter. For a 2,000-page
“report” it does. JasperReports has virtualizers that move filled pages to disk:
JRSwapFile swap = new JRSwapFile(System.getProperty("java.io.tmpdir"), 4096, 1024);
JRSwapFileVirtualizer virtualizer = new JRSwapFileVirtualizer(50, swap, true);
params.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
try {
JasperPrint print = JasperFillManager.fillReport(template, params, dataSource);
JasperExportManager.exportReportToPdfStream(print, out);
} finally {
virtualizer.cleanup();
}
But if you need this, ask first if the user really wants a PDF. Often they want the data, and an Excel export is the better product.
Excel exports with Apache POI
POI has three ways to write .xlsx:
XSSFWorkbook: the full in-memory model. Easy, supports everything, but every cell is an object. Large exports use a lot of heap.SXSSFWorkbook: a streaming writer on top of XSSF. It keeps a window of rows in memory (100 by default) and writes older rows to a temporary file. Memory stays flat as the row count grows.HSSFWorkbook: the old.xlsformat. Limited to 65,536 rows. I do not use it for new code.
The .xlsx format itself allows 1,048,576 rows per sheet. If an export can grow beyond that, split
sheets or offer CSV.
public void writeOrders(Stream<OrderRow> rows, OutputStream out) throws IOException {
SXSSFWorkbook wb = new SXSSFWorkbook(200);
wb.setCompressTempFiles(true);
try {
Sheet sheet = wb.createSheet("Orders");
DataFormat fmt = wb.createDataFormat();
CellStyle dateStyle = wb.createCellStyle();
dateStyle.setDataFormat(fmt.getFormat("yyyy-mm-dd"));
CellStyle moneyStyle = wb.createCellStyle();
moneyStyle.setDataFormat(fmt.getFormat("#,##0.00"));
Row header = sheet.createRow(0);
String[] titles = {"Order no", "Date", "Customer", "Amount"};
for (int i = 0; i < titles.length; i++) {
header.createCell(i).setCellValue(titles[i]);
}
int r = 1;
for (OrderRow o : (Iterable<OrderRow>) rows::iterator) {
Row row = sheet.createRow(r++);
row.createCell(0).setCellValue(o.orderNo()); // text, keeps leading zeros
Cell date = row.createCell(1);
date.setCellValue(o.orderDate()); // LocalDate
date.setCellStyle(dateStyle);
row.createCell(2).setCellValue(o.customer());
Cell amount = row.createCell(3);
amount.setCellValue(o.amount().doubleValue());
amount.setCellStyle(moneyStyle);
}
sheet.createFreezePane(0, 1);
wb.write(out);
} finally {
wb.close();
wb.dispose(); // deletes the temporary files
}
}
SXSSF rules that matter:
- Create cell styles once and reuse them. Creating a style per cell is a classic bug. The file gets huge and Excel complains about too many styles.
autoSizeColumnneeds the column data, which SXSSF has already flushed. You can track columns withtrackAllColumnsForAutoSizing(), but it is slow on big sheets. I set fixed widths withsheet.setColumnWidth.- You cannot go back to rows that were flushed. Write top to bottom.
- Temporary files go to
java.io.tmpdir. In a container with a small or read-only temp directory, large exports fail there, not in the heap.
EasyExcel
EasyExcel from Alibaba is a layer on top of POI. It is popular in Chinese Java projects. You describe the columns with annotations, and it writes in a streaming way.
public class OrderExportRow {
@ExcelProperty("Order no")
private String orderNo;
@ExcelProperty("Date")
@DateTimeFormat("yyyy-MM-dd")
private LocalDate orderDate;
@ExcelProperty("Amount")
@NumberFormat("#,##0.00")
private BigDecimal amount;
// getters and setters
}
try (ExcelWriter writer = EasyExcel.write(out, OrderExportRow.class).build()) {
WriteSheet sheet = EasyExcel.writerSheet("Orders").build();
orderRepository.forEachPage(1000, page -> writer.write(page, sheet));
}
Write in batches, as above, not with one doWrite(hugeList) call. Otherwise the list itself fills the heap
before EasyExcel can help.
A few notes:
- The current version is 4.0.3 (September 2024). Version 4.0 moved to POI 5.2.5 and added JDK 21 support.
- EasyExcel brings its own POI version. If your project also uses POI directly, or JasperReports’ Excel
exporter, align the POI versions in
dependencyManagement, or you getNoSuchMethodErrorat runtime. - Check what
@NumberFormatand@DateTimeFormatproduce in your version: a numeric cell with a format, or a formatted text cell. Open the file and try to sum the column. Users will notice the difference, so I check it in a test (see below) instead of trusting the annotation name. - It is mostly maintained by one company and a small team. Look at the recent activity in the repository before you make it a core dependency. For small projects I use plain POI and avoid the extra layer.
My rule: one or two exports in a project, plain POI SXSSF. Many exports with simple flat rows, EasyExcel saves code.
Streaming the export from Spring Boot
Do not build the file in a byte[] and return it. For big exports, write directly to the response:
@GetMapping("/exports/orders.xlsx")
public ResponseEntity<StreamingResponseBody> exportOrders(@RequestParam int year) {
StreamingResponseBody body = out ->
transactionTemplate.executeWithoutResult(tx ->
exporter.writeOrders(orderDao.streamByYear(year), out));
String filename = "orders-" + year + ".xlsx";
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.attachment()
.filename(filename, StandardCharsets.UTF_8)
.build().toString())
.contentType(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(body);
}
(writeOrders throws IOException; wrap it in an UncheckedIOException inside the lambda.)
Things to watch:
StreamingResponseBodyruns on another thread, after the controller method returned. A@Transactionalon the controller does not cover it. That is why the example opens a transaction inside the lambda withTransactionTemplate.- Streaming rows from the database needs driver support. With PostgreSQL,
fetchSizeonly works inside a transaction (autocommit off). With MySQL Connector/J, you needuseCursorFetch=trueor the special streaming fetch size. Otherwise the driver loads the whole result set into memory and the streaming writer does not help. - The async request timeout (
spring.mvc.async.request-timeout) applies. Set it for long exports. - Once the first bytes are sent, the status is 200. If the export fails halfway, the user gets a broken file and no error. For exports that take minutes, I prefer a background job that writes to a file or object storage, and a download link when it is done.
- Limit concurrent exports. A few users clicking “export all” at the same time can use all database connections.
- Use the filename with
UTF-8(as above) if names can contain non-ASCII characters. The header then carries both a fallback and an encoded name.
Formatting numbers and dates
Most complaints about exports are about formats, not about content:
- Write numbers as numeric cells and dates as date cells with a format. Text that looks like a number cannot be summed, and Excel shows a warning triangle on every cell.
- Excel stores numbers as doubles with about 15 significant digits. Long IDs, phone numbers, bank account numbers and codes with leading zeros must be written as text.
BigDecimalmoney values become doubles in the cell. For display with two decimals this is fine. If accountants need exact values, discuss it with them; sometimes the answer is CSV with a fixed format.- The cell format string decides how a date looks, and Excel shows it in the user’s locale for built-in
formats. If you write
yyyy-mm-ddexplicitly, everybody sees ISO dates. I prefer that for exports. - Time zones: convert to the user’s or the business time zone before writing. A cell has no time zone.
- In JasperReports, set
REPORT_LOCALEandREPORT_TIME_ZONEparameters, and use patterns on the text fields. Do not format numbers into strings in Java before passing them to the report.
Testing report output
I test reports at three levels.
Data level. The code that builds the rows for the report or export is a normal function. Test it like any other code. Most bugs are here.
Excel files. Generate a small export in a test, open it again with POI, and check headers, cell types and formats:
@Test
void amountIsNumericWithTwoDecimals() throws Exception {
var out = new ByteArrayOutputStream();
exporter.writeOrders(Stream.of(sampleRow()), out);
try (var wb = new XSSFWorkbook(new ByteArrayInputStream(out.toByteArray()))) {
Cell amount = wb.getSheet("Orders").getRow(1).getCell(3);
assertThat(amount.getCellType()).isEqualTo(CellType.NUMERIC);
assertThat(amount.getCellStyle().getDataFormatString()).isEqualTo("#,##0.00");
}
}
PDF files. Pixel comparison is fragile. I extract the text with Apache PDFBox and check that the
important values are there: invoice number, totals, a CJK customer name. I also check that the fonts are
embedded. On the command line, pdffonts invoice.pdf from poppler-utils shows it quickly. A test that
renders a PDF with Chinese text inside the real Docker image catches the font problem before a user does.
What I still check by hand: the layout of a new template, printed on paper once. Page breaks and margins look different on paper than on screen, and no test I wrote catches that.