Skip to content
sheetsmith

Output and delivery

Writing to a file and attaching to an e-mail

Section titled “Writing to a file and attaching to an e-mail”
// To a file: stream method
try (OutputStream out = Files.newOutputStream(Path.of("report.xlsx"))) {
sheetsmith.generate(sheets, out);
}
// As an attachment: byte method
byte[] file = sheetsmith.generate(sheets);
helper.addAttachment("report.xlsx", new ByteArrayResource(file),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
List<SheetData<?>> sheets = List.of(SheetData.of("Customers", CustomerRow.class, loadCustomers()));
byte[] file = sheetsmith.generate(sheets); // errors happen here, before the response is touched
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=\"customers.xlsx\"");
response.setContentLength(file.length);
response.getOutputStream().write(file);
}

For the Spring MVC equivalent see section 2.3.

@ExcelSheet(autoSizeColumns = false, freezeHeader = true)
public record MovementRow(
@ExcelColumn(header = "Id", order = 10, width = 12) long id,
@ExcelColumn(header = "Date", order = 20, width = 12, format = "dd/mm/yyyy") LocalDate date,
@ExcelColumn(header = "Description", order = 30, width = 50) String description,
@ExcelColumn(header = "Amount", order = 40, width = 14, format = "#,##0.00") BigDecimal amount) {
}

Explicit widths and no automatic sizing; a heap sized from the measurements in section 12.3; bounded concurrency; data split across files beyond a few hundred thousand rows.