In modern Spring Boot applications, the cleanest approach is to return a ResponseEntity . This avoids direct manipulation of the HttpServletResponse and follows standard Spring patterns.
: For .xlsx files, use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet . For older .xls files, use application/vnd.ms-excel . download excel file from byte array java
@GetMapping("/download/excel") public ResponseEntity downloadExcel() { // 1. Obtain your Excel data as a byte array byte[] excelBytes = excelService.generateExcelContent(); // 2. Prepare headers HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=report.xlsx"); // 3. Define the correct Media Type for .xlsx files MediaType excelMediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); return ResponseEntity.ok() .headers(headers) .contentType(excelMediaType) .body(new ByteArrayResource(excelBytes)); } Use code with caution. In modern Spring Boot applications, the cleanest approach
: The attachment directive ensures the browser prompts a "Save As" dialog instead of attempting to display the raw binary data. 2. Standard Servlet Implementation For older
To download an Excel file from a byte array in Java, you must write the raw binary data to the HTTP response output stream while setting specific headers that instruct the browser to treat the data as a downloadable spreadsheet. 1. Spring Boot Implementation ( ResponseEntity )
30 Aug 2022 — Sorted by: 2. I write it. my code: ByteArrayOutputStream outputStream = new ByteArrayOutputStream(20000000); String resultBase64 = Stack Overflow Generate large Excel files and response from API