2016-11-18 95 views
1

我正在使用Spring Framework提供的REST Web服務。 我需要下載一個Excel工作表,但我還需要在某些選定參數的基礎上下載工作表。我正在將一個請求類對象作爲正文發送到POST Rest呼叫(@RequestBody)使用POST Rest服務下載Excel

我無法使用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 

這是我的方法簽名

+0

你爲什麼使用POST?爲什麼不在查詢字符串中使用帶有搜索參數的GET? – jannis

+0

搜索參數是一種對象類型:( – jasmeet24

+0

你是說你不控制前端應用程序? – jannis

回答

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規範的接口進行交互。

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

} 
0

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