Java – An error occurred while the Java REST client was receiving and saving an excel response (byte array).

An error occurred while the Java REST client was receiving and saving an excel response (byte array)…. here is a solution to the problem.

An error occurred while the Java REST client was receiving and saving an excel response (byte array).

I

have the Spring REST service return the excel file (XLS) as a byte array, and I need to write the appropriate client code to receive this response and save the file. Able to get a byte array response, but the following error occurs when converting it to an excel workbook (HSSFWorkbook).

org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x0005060000100809, expected 0xE11AB1A1E011CFD0 – Your file appears not to be a valid OLE2 document.

I tried the following without success

  1. Verify that the file is valid by saving it in the service before returning the response.
  2. An attempt was made to send an InputStream instead of a byte array
  3. Try using ResponseEntity
    And so on

Server-side code

HSSFWorkbook workbook = //code to generate the workbook
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
byte[] response = outputStream.toByteArray();

Any help is greatly appreciated.

Solution

Find the problem and fix it.

Server-side code

            HSSFWorkbook workbook = //workbook creation call
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            response = outputStream.toByteArray();
            headers = new HttpHeaders();
            headers.setAccessControlExposeHeaders(Collections.singletonList("Content-Disposition"));
            headers.set("Content-Disposition", "attachment; filename=download.xls");
            headers.setAccessControlExposeHeaders(Collections.singletonList("Content-Type"));
            headers.set("Content-Type","application/vnd.ms-excel");
            outputStream.close();

Client code

String uri = //URI
    RestTemplate restTemplate = new RestTemplate();
        input object
    ResponseEntity<byte[]> result = restTemplate.postForEntity(uri, input, byte[].class);
    if(result!=null && result.getStatusCodeValue() == 200 && result.getBody()!=null && result.getBody().length>0)
    {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(result.getBody());
        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
        FileOutputStream outputStream = new FileOutputStream("output\\download.xls");
        workbook.write(outputStream);
        inputStream.close();
        workbook.close();
        outputStream.close();
    }

Related Problems and Solutions