【发布时间】: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