I've seen many similar questions elsewhere, but have not been able to resolve this problem.
I want to download an Excel document in my application using Apache POI (3.17). I am generating the document in a Spring service then passing this as a response back to the JavaScript client to be downloaded. However, the file is corrupted because the "file format or file extension is not valid".
Spring service:
final Workbook workbook = new XSSFWorkbook();
final Sheet sheet = workbook.createSheet("Test");
Row row = sheet.getRow(1);
if (row == null)
{
row = sheet.createRow(1);
}
Cell cell = row.getCell(0);
if (cell == null)
{
cell = row.createCell(0);
}
cell.setCellValue("Testing123");
final ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook.write(outByteStream);
outArray = outByteStream.toByteArray();
outByteStream.flush();
outByteStream.close();
workbook.close();
Servlet:
final ByteArrayResource resource = new ByteArrayResource(
this.downloadService.downloadExcel(request, response, baseRequest));
final HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename());
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.body(resource);
JavaScript client:
var contentTypeHeader = 'application/vnd.ms-excel';
var blob = new Blob([result],{type: contentTypeHeader});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
Where am I going wrong?