Skip to content

Instantly share code, notes, and snippets.

@rlcc885
Last active December 12, 2022 15:42
Show Gist options
  • Select an option

  • Save rlcc885/f2d35ce5f43de777de217ed25b86a91e to your computer and use it in GitHub Desktop.

Select an option

Save rlcc885/f2d35ce5f43de777de217ed25b86a91e 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