Skip to content

Instantly share code, notes, and snippets.

@NeftaliYagua
Forked from rlcc885/RestControllerExcel.java
Created December 12, 2022 15:42
Show Gist options
  • Save NeftaliYagua/fb10ce8b4ae8c5babd857b2166bc4262 to your computer and use it in GitHub Desktop.
Save NeftaliYagua/fb10ce8b4ae8c5babd857b2166bc4262 to your computer and use it in GitHub Desktop.
Spring boot REST Service - Apache POI force download excel
public class RestControllerExcel{
@GetMapping(value="/downloadTemplate")
public ResponseEntity<ByteArrayResource> downloadTemplate() throws Exception {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
XSSFWorkbook workbook = createWorkBook(); // creates the workbook
HttpHeaders header = new HttpHeaders();
header.setContentType(new MediaType("application", "force-download"));
header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=ProductTemplate.xlsx");
workbook.write(stream);
workbook.close();
return new ResponseEntity<>(new ByteArrayResource(stream.toByteArray()),
header, HttpStatus.CREATED);
} catch (Exception e) {
log.error(e.getMessage());
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment