【问题标题】:POI - save exported file to a clientPOI - 将导出的文件保存到客户端
【发布时间】:2011-12-13 07:43:50
【问题描述】:

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

部分方法:

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(); 

【问题讨论】:

  • 那么您是在某些网络应用程序中生成此工作簿服务器端的吗?您需要将它保存在服务器端的某个地方并将您的客户端重定向到它(正确设置 mime 类型等等)。大多数浏览器都会弹出“文件保存”对话框,您的客户端可以选择存储位置。
  • Jj,JSF 网络应用程序。我单击该按钮并在服务器上自动创建 excel(例如 c:\export.xls)。但我不知道如何开始对话以选择另一条路径..
  • 我不知道关于 JSF 的深蹲,但有一个 SO 答案似乎可以满足您的需求:stackoverflow.com/questions/2914025/…

标签: java jsf apache-poi


【解决方案1】:

如果我没听错,您需要通过 http 将文件传回客户端。 您可以在HttpServletResponse 中使用getOutputStream() 方法来代替FileOutputStream

代码应如下所示:

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();

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

【讨论】:

  • 谢谢,这几乎是我所需要的。我已经更新了我的问题。请使用它并更新您的答案,我会接受它:)
  • @gaffcz :我很高兴我的回答有所帮助。但是,由于我对 JSF 一无所知,因此我不愿意在答案中添加 JSF 代码。我只是指出你需要一个不同的输出流,所以你在哪个框架中并不重要:)
猜你喜欢
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
相关资源
最近更新 更多