如何在不将其保存在硬盘上的情况下发送新创建的excel文件?

时间:2017-02-10 09:37:49

标签: java web-services

    List<String> headerRow = Arrays.asList("col1", "col2", "col3","col4","col5"); 
    // Creates a xlsx workbook !!
    XSSFWorkbook wb = ExcelHelper.writeToXlsxExcelFile(headerRow,EjbHelper.getAccountEJb().getCustomersByscPartyNumber("9B7W5")); 
    //Creating a file to dump xlsx
    String fileLocation = "d://try.xlsx";
    FileOutputStream fout = new FileOutputStream(fileLocation);
    workbook.write(fout);
    //Want to Create a Webservice to send response without saving file to hard-disk 
    ResponseBuilder response = Response.ok((Object)fout);
    response.header("Content-Disposition","attachment; filename=" + "ResourceInformation.xlsx");
    return response.build();

上面的代码片段创建了一个xlsx文件然后通过响应发送它。我想知道有没有办法直接发送xlsx文件而不在硬盘上创建文件?

1 个答案:

答案 0 :(得分:0)

我想更简单的方法是直接使用HttpServletResponse

 public void yourMethod(@Context HttpServletResponse httpServletResponse) {
    List<String> headerRow = Arrays.asList("col1", "col2", "col3","col4","col5"); 
    Workbook wb = ExcelHelper.writeToXlsxExcelFile(headerRow,EjbHelper.getAccountEJb().getCustomersByscPartyNumber("9B7W5"));
    response.setHeader("Content-Disposition","attachment; filename=" + "ResourceInformation.xlsx");
    wb.write(response.getOutputStream());
    response.flushBuffer();
}