使用POST Rest服务下载Excel

时间:2016-11-18 10:36:11

标签: excel rest post

我正在使用Spring Framework提供的REST Web服务。 我需要下载excel表,但我还需要根据一些选定的参数下载表。我正在将一个请求类对象作为Body发送给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 

这是我的方法签名

3 个答案:

答案 0 :(得分:1)

我发现这个帖子Return Excel downloadable file from Spring可能有用。

我还认为你强迫的内容类型(产生= MediaType.APPLICATION_JSON_VALUE)可能会阻碍,至少就我能理解的问题而言。我认为你应该在那里强制使用EXCEL内容类型(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构建ResponseEntity。然后,ResourceHttpMessageConverter将为您复制字节,如上所述。 Spring MVC使您更容易,而不是让您与Servlet规范中的接口进行交互。

答案 1 :(得分:1)

@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");
    }

}

答案 2 :(得分:0)

ResponseBuilder响应= Response.ok(文件);         response.header(" Content-Disposition"," attachment; filename = \"" + fileName2 +" \"");         return response.build();