我有Spring REST服务以字节数组形式返回excel文件(XLS),并且需要编写适当的客户端代码来接收此响应并保存文件。能够获取字节数组响应,但是在将其转换为excel工作簿(HSSFWorkbook)时却遇到以下错误
org.apache.poi.poifs.filesystem.NotOLE2FileException:标头签名无效;读取0x0005060000100809,预期为0xE11AB1A1E011CFD0-您的文件似乎不是有效的OLE2文档。
我尝试了以下方法,但是没有运气
服务端代码
HSSFWorkbook workbook = //code to generate the workbook
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
byte[] response = outputStream.toByteArray();
非常感谢您的帮助。
答案 0 :(得分:0)
找到问题并解决。
服务器端代码
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();
客户端代码
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();
}