我正在使用 Spring Framework 提供的 REST Web 服务。 我需要下载 Excel 工作表,但我还需要根据某些选定的参数下载该工作表。我将请求类对象作为正文发送到 POST Rest 调用(@RequestBody)
我无法使用 POST 方法下载 Excel。请帮助我实现这一目标。
@RequestMapping(value = "/search/export", method = RequestMethod.POST,, produces = MediaType.APPLICATION_JSON_VALUE)
public void searchResultToExcel(@RequestBody SearchRequest searchRequest, HttpServletResponse response, HttpServletRequest request) throws Exception
这是我的方法签名
最佳答案
我找到了这个帖子Return Excel downloadable file from Spring这可能有用。
我还认为您强制的内容类型(产生= MediaType.APPLICATION_JSON_VALUE)可能会妨碍,至少就我能理解的问题而言。我认为您应该强制使用 EXCEL 内容类型 (application/vnd.ms-excel)。
它说:
您需要设置 Content-Disposition
header 。
response.setHeader("Content-disposition","attachment; filename=" + yourFileName);
并将字节直接写入响应OutputStream
。
File xls = new File("exported.xls"); // or whatever your file is
FileInputStream in = new FileInputStream(xls);
OutputStream out = response.getOutputStream();
byte[] buffer= new byte[8192]; // use bigger if you want
int length = 0;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
上面的内容比较旧。您可以使用 FileSystemResource
构造一个 ResponseEntity
现在。一个ResourceHttpMessageConverter
然后将按照我上面的建议为您复制字节。 Spring MVC 让您变得更简单,而不是让您与 Servlet 规范中的接口(interface)进行交互。
关于excel - 使用 POST Rest 服务下载 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40674906/