使用POST Rest服务下载Excel

我正在使用Spring Framework提供的REST Web服务。 我需要下载一个Excel工作表,但我也需要根据一些选定的参数来下载表格。 我发送一个请求类对象作为正文到一个POSTrest调用(@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 

这是我的方法签名

我发现这个线程从Spring返回Excel可下载的文件 ,可能是有用的。

我也认为你正在强制的内容types(生产= MediaType.APPLICATION_JSON_VALUE)可能是阻碍,至less据我了解的问题。 我认为你应该强迫一个EXCEL内容types(application / vnd.ms-excel)。

它说:

您需要设置Content-Disposition标题。

 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构buildResponseEntity 。 一个ResourceHttpMessageConverter然后将复制字节,如上所示,为你。 Spring MVC使你更简单,而不是让你与Servlet规范的接口交互。

 @Post @Path("downloadMyReport") @Produces("application/excel") public static Response generatemyExcelReport()throws BusinessException { try { File file=null; Date reportDate=new Date() ; path="/home/Documents/excelReport/" file=getReportByName(path); if(file==null){ logger.info("File is null"); else{ name=capitalizeFirstLater(name); getReportSummary(reportDate); FileUtils.writeByteArrayToFile(new File(path),createExcelForReport(fileName,path)); file=getReportByName(path); } ResponseBuilder response = Response.ok(file); response.header("Content-Disposition", "attachment; filename=\"" + fileName2 + "\""); return response.build(); } }catch (BusinessException e) { throw e; }catch (Exception e) { logger.error("Exception while generating ExcelSheetForMyReport {}",Utils.getStackTrace(e)); throw new BusinessException("Error in downloading ExcelSheetForMyReport"); } } 

ResponseBuilder response = Response.ok(file); response.header(“Content-Disposition”,“attachment; filename = \”“+ fileName2 +”\“”); return response.build();