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

时间:2011-12-13 07:43:50

标签: 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();
  }  
}

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

解决方案(基于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(); 

1 个答案:

答案 0 :(得分: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();

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