Implementing Data Export

1. Implementing CSV Export

Example: Streaming CSV

@GetMapping(value = "/orders/export.csv", produces = "text/csv")
public ResponseEntity<StreamingResponseBody> export() {
    StreamingResponseBody body = out -> {
        try (var w = new OutputStreamWriter(out, UTF_8);
             var p = new PrintWriter(w)) {
            p.println("id,customer,total");
            orderRepo.streamAll().forEach(o ->
                p.printf("%s,%s,%d%n", o.id(), csv(o.customerName()), o.total().cents()));
        }
    };
    return ResponseEntity.ok()
        .header("Content-Disposition", "attachment; filename=orders.csv")
        .body(body);
}

2. Implementing Excel Export

LibraryDetail
Apache POI (XSSF)Full feature set; high memory
SXSSFStreaming; large files
EasyExcel (Alibaba)Lower memory than POI
Use casesFormulas, multi-sheet, formatting

3. Implementing PDF Export

LibraryDetail
OpenPDFFork of iText 4 (LGPL)
iText 7Powerful; AGPL/commercial
Apache PDFBoxLower-level
Flying Saucer + ThymeleafHTML/CSS → PDF

4. Implementing JSON Export

Example: Streaming JSON array

StreamingResponseBody body = out -> {
    try (JsonGenerator g = mapper.createGenerator(out)) {
        g.writeStartArray();
        orderRepo.streamAll().forEach(o -> g.writeObject(toDto(o)));
        g.writeEndArray();
    }
};

5. Implementing Streaming Export for Large Datasets

PatternDetail
Cursor / scrollAvoid loading all into memory
JDBC fetchSizeHint streaming reads (e.g., 1000)
Servlet streamingStreamingResponseBody
Read-only TXLower DB overhead
Detach entitiesPrevent JPA cache bloat

6. Implementing Async Export Generation

StepDetail
Submit jobPOST returns 202 + job ID
WorkerGenerates file in background
StorageUpload to S3
NotifyEmail or in-app on completion
DownloadPre-signed URL with expiry

7. Implementing Export Format Selection

MechanismDetail
Accept headerContent negotiation
Query param?format=csv
Path suffix/export.csv
Allow-listReject unknown formats

8. Implementing Export Compression

FormatDetail
.gzSingle file
.zipMulti-file bundle
.tar.gzUnix-friendly multi-file
Streaming zipZipOutputStream

9. Implementing Export Pagination

ApproachDetail
Multiple filesSplit by row count
Date partitioningOne file per day/month
Manifest fileLists all parts

10. Handling Export Field Selection

MechanismDetail
fields query?fields=id,total,status
Per-role projectionHide sensitive columns
TemplatesUser-saved column sets

11. Implementing Export Scheduling

FeatureDetail
Cron scheduleDaily/weekly/monthly
DeliveryEmail link, S3, SFTP
Filter setSaved query
Failure alertNotify owner on error

12. Implementing Export Audit Trail

FieldDetail
actorWho exported
filtersWhat query
row countHow much data
file hashIntegrity
retentionAuto-delete after N days
Warning: Bulk PII exports are a top breach vector — alert on anomalous export volumes.