Generating Excel, PDF & CSV, plus async export jobs
Apache POI vs fastexcel, OpenPDF, CSV pitfalls (formula injection, encoding), streaming large files, and the 202-Accepted async export job pattern.
Libraries
| Format | Library | Notes |
|---|---|---|
| XLSX | Apache POI (RM) | Full feature set (styles, formulas, charts); memory-heavy. Use SXSSFWorkbook to stream big files |
| XLSX | fastexcel (SperoTek) | Fast, low-memory writer with fewer features |
| OpenPDF (both) | LGPL fork of iText 4. Programmatic layout | |
| HTML → PDF (OpenHTMLtoPDF, Flying Saucer, headless Chrome) | Design with HTML/CSS templates instead of code | |
| CSV | Hand-written or Commons CSV / OpenCSV | Simple, universal |
Async export jobs
A 50,000-line ledger PDF can take 20 seconds. Don’t block the request:
POST /reports/export {type, period} -> 202 Accepted { jobId } (job row status=PENDING)
queue / async worker generates file -> status=COMPLETE, content=bytes
GET /exports/{jobId} -> { status: "COMPLETE" } (poll, or push via SSE)
GET /exports/{jobId}/download -> file (Content-Disposition: attachment)
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()
.filename("trial-balance-2026-11.xlsx", UTF_8).build().toString())
.body(job.getContent());
In your projects
report/application/ExcelExporter.java · export/* · ExportConsumer · ExportDeadLetterConsumer · ExportJobCleanupSchedulerPOI for Excel and OpenPDF for PDF. Export requests go onto RabbitMQ export.queue, ExportConsumer generates the file into ExportJob.content, failures go to the DLQ and mark the job FAILED, completion is pushed over SSE, and jobs are deleted after 60 days. A user guide .docx ships in resources/documents.
reporting/application/ReportExporter · ReportExportService · AccountCsv · JournalCsv · ChartImporterOpenPDF + fastexcel. Async exports via @ApplicationModuleListener with a download endpoint and hourly cleanup. CSV export and import for the chart of accounts and journals (/accounts/import is multipart). There’s also a ReportBenchmarkIT performance test, because reports must stay fast as ledgers grow.
Related concepts you must know
- Streaming. For huge exports, write directly to the response
OutputStream(POISXSSFWorkbook, a CSV writer) instead of building abyte[]. - Encoding. Write CSV as UTF-8 with a BOM if Excel users need accented characters, and use
RFC 4180quoting. - Import validation. Validate every row, report errors per row, and run inside a transaction (all or nothing) or a staging table.
- Idempotent imports. Re-uploading the same file shouldn’t duplicate accounts.
- Report correctness tests. Golden-file tests compare generated totals with known-good values.