POI - 将导出的文件保存到客户端

gaf*_*fcz 3 java jsf apache-poi

我正在将dataTable(绑定dataList)导出到excel文件,调用以下方法 xlsWorkBookPrepare("c:\\export.xls");

方法的一部分:

public void xlsWorkBookPrepare(String file) throws IOException
{
  /* prepare of workbook */
  Workbook wb = new HSSFWorkbook();
  Map<String, CellStyle> styles = Style.createStyles(wb);
  ... 

  for (FoodList item : dataList)
  { 
    ...
  }  

  /* create file */
  FileOutputStream fileOut;
  try 
  {
    fileOut = new FileOutputStream(file);
    wb.write(fileOut);
    fileOut.flush();
    fileOut.close();
  } 
  catch (FileNotFoundException e) 
  {
    e.printStackTrace();
  }  
}
Run Code Online (Sandbox Code Playgroud)

但路径与服务器有关.如何将它保存在客户端?

解决方案(基于Rangi Lin的回答):

HttpServletResponse res = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
res.setContentType("application/vnd.ms-excel");  
res.setHeader("Content-disposition",  "attachment; filename=test.xls"); 

try 
{
  ServletOutputStream fileOut = res.getOutputStream();
  wb.write(fileOut);
  fileOut.flush();
  fileOut.close();
} 
catch (FileNotFoundException e) 
{
  e.printStackTrace();
}  
FacesContext faces = FacesContext.getCurrentInstance();  
faces.responseComplete(); 
Run Code Online (Sandbox Code Playgroud)

Ran*_*Lin 8

如果我说得对,你需要通过http将文件传回客户端.而不是FileOutputStream,你可以使用getOutputStream()方法HttpServletResponse.

代码应如下所示:

String fileName = "excel.xls";
HttpServletResponse response = getResponse(); // get ServletResponse
response.setContentType("application/vnd.ms-excel"); // Set up mime type
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
OutputStream out = response.getOutputStream()
wb.write(out);
out.flush();
Run Code Online (Sandbox Code Playgroud)

注意:我没有测试它,但你应该能够理解它.