excel - 使用 POST Rest 服务下载 Excel

标签 excel rest post

我正在使用 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/

相关文章:

json - 带 json 参数的 curl GET 请求

json - Spring MVC : post request and json object with array : bad request

c# - 后台 Excel 线程未被杀死 C#

Excel 超链接 - 跳转到单元格并滚动窗口

excel - EXCEL的多层下拉菜单

excel - 典型 Excel 365 对象的 Microsoft 文档引用 "an object in the Applies To list",但 "Applies to list"在哪里?

spring - 升级到 Spring boot 2.x 后请求映射不起作用

Perl REST 流布局

javascript - jQuery .post 在完成和失败时不返回数据

php - 限制发布sql?