Export JSF Datatable as Excel

9.4k views Asked by At

I am kind of new to JSF Web Development. I have xhtml page that has submit. Once the user click on submit button, it export the excel page. My code is working very well with submit button,but it prints table on screen. I need help as a excel spreadsheet.

1

There are 1 answers

4
Luiggi Mendoza On

JSF doesn't provide any functionality to export data from a <h:dataTable> into a specific format. You may use PrimeFaces (an external library) that has a <p:dataExporter> component that provides this functionality, check the demo.

If you don't want to use PrimeFaces, then you should write the Excel file by yourself inside an action and fire a file download with the file created on the fly. Here's a small sample of how to do this.

JSF code:

<h:dataTable value="#{bean.list}" var="item">
    <!-- Columns and relevant data to show to users... -->
</h:dataTable>
<br />
<h:commandLink value="Export to Excel"
    action="#{exporterBean.export(bean.list)}" />

Java code:

@ManagedBean
@ApplicationScoped
public class ExporterBean {
    public void export(List<?> data) {
        //create the Excel file on the fly
        //use Apache POI or another library to do it
        //use the data in List<?> data to export the relevant data

        //fire a file download...
    }
}

Relevant info for this: