我让 Spring REST 服务返回 excel 文件 (XLS) 作为字节数组,需要编写适当的客户端代码来接收此响应并保存文件。能够获得字节数组响应,但在将其转换为 excel 工作簿 (HSSFWorkbook) 时出现以下错误
org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x0005060000100809, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document.
我尝试了以下但没有成功
- 通过在返回响应之前将文件保存在服务中来验证该文件是否有效。
- 试图发送 InputStream 而不是字节数组
- 尝试使用 ResponseEntity 等等
服务端代码
HSSFWorkbook workbook = //code to generate the workbook
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
byte[] response = outputStream.toByteArray();
非常感谢任何帮助。
最佳答案
找到问题并修复它。
服务端代码
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();
}
关于java - Java REST 客户端接收和保存 excel 响应(字节数组)时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051872/