我想导出 <rich:dataTable>
的内容或 <rich:extendedDataTable>
脱颖而出。
我看到 PrimeFaces 具有“导出器功能”http://www.primefaces.org/showcase/ui/exporter.jsf
我希望能够在不使用 PrimeFaces 的情况下执行与此类似的操作,但使用 richFaces(版本 3.3.3)...(我想在某个时候迁移到 RichFaces 4 future 但我现在坚持使用 3.3.3)
我了解到可以使用 http://poi.apache.org/ 构建您自己的但我不知道从哪里开始实现这样的事情......
任何关于如何最好地执行所需的导出和示例的想法将不胜感激!
最佳答案
在 JSF 中使用 POI 与在普通 Java 中使用 POI 并没有什么不同。只需拥有代表每条记录的项目集合。您必须已经拥有它,因为您正在使用也采用此类集合的数据表。您只需迭代完全相同的集合即可在 POI 中创建 Excel 工作表。
这是一个启动示例,其中 items
是 List<Item>
您也在数据表中使用:
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("sheet title");
int rowIndex = 0;
for (Item item : items) {
Row row = sheet.createRow(rowIndex++);
int columnIndex = 0;
row.createCell(columnIndex++).setCellValue(item.getId());
row.createCell(columnIndex++).setCellValue(item.getName());
row.createCell(columnIndex++).setCellValue(item.getValue());
// ...
}
workbook.write(someOutputStream); // Write the Excel result to some output.
为了将其作为 JSF 响应的下载提供,您需要提供 ExternalContext#getResponseOutputStream()
作为someOutputStream
.您还需要设置响应内容类型(以便浏览器知道要与之关联的应用程序)和响应内容配置(以便它作为附件打开并具有有效的文件名)。
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
externalContext.responseReset();
externalContext.setResponseContentType("application/vnd.ms-excel");
externalContext.setResponseHeader("Content-Disposition", "attachment;filename=export.xls");
workbook.write(externalContext.getResponseOutputStream());
context.responseComplete(); // Prevent JSF from performing navigation.
最后, FacesContext#responseComplete()
必须调用以防止 JSF 执行默认导航任务(这只会通过将导航页面的一些 HTML 输出附加到末尾来破坏 Excel 文件)。
请注意,上面的 JSF 示例假定 JSF 2.x。如果您实际上使用的是 JSF 1.x,它缺少一些便利 ExternalContext
委托(delegate)方法,那么你需要获取原始的 HttpServletResponse
通过 ExternalContext#getResponse()
并对其执行操作。另见 How to provide a file download from a JSF backing bean?
关于java - 如何导出丰富的:dataTable to excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13199185/