gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:15:23 25 4
gpt4 key购买 nike

我正在通过 xlsWorkBookPrepare("c:\\export.xls");

调用以下方法将 dataTable(绑定(bind) 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();

最佳答案

如果我没看错,你需要通过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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com