我正在通过 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();
最佳答案
如果我没看错,你需要通过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();
注意:我没有测试它,但你应该能理解。
关于java - POI - 将导出的文件保存到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8485809/