Error in Java REST client to receive and save the excel response(byte array)

Viewed 1270

I have the Spring REST service returns the excel file(XLS) as byte array and need to write the appropriate client code to receive this response and save the file. Was able to get the byte array response but while converting it to excel workbook(HSSFWorkbook) getting the below error

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 but no luck

  1. verified that the file is valid by saving it in the service before returns in response.
  2. Tried to send the InputStream instead of byte array
  3. Tried using ResponseEntity etc

service 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.

1 Answers

Found the issues and fixed 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 side 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