Using POIs in JSF is actually no different than using POIs in plain Java. You just have a collection of items representing each entry. You should already have this when using data that also takes such a collection. You just need to iterate over the exact same collection to create an Excel worksheet in a POI.
Here's a startup example, where items is a List<Item> , which you also use in datatable:
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());
To suggest this as loading a JSF response, you need to provide ExternalContext#getResponseOutputStream() as someOutputStream . You also need to set the type of response content (so that the browser knows which application is associated with it) and the location of the response content (so that it is opened as an attachment and that it has a valid file name).
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.
In the end, FacesContext#responseComplete() must be called to prevent the JSF from executing the default navigation task (which would only damage the Excel file by adding some HTML output to the navigation page at the end).
Note that the above JSF example assumes JSF 2.x. If you are actually using JSF 1.x, which lacks several ExternalContext delegate methods, you need to take the raw HttpServletResponse to ExternalContext#getResponse() and follow through on it. See Also. How to ensure that a file is loaded from the JSF bean database?
source share