Export JSF Datatable as Excel, PDF, CSV, XML

PrimeFaces ships with an exporter feature that can export any data presented with a JSF datatable to various formats such as Excel, PDF, CSV and XML.
Exporter is implemented as an actionListener so it can be attached to any command component like a button or a command link.
Here is a regular JSF datatable;

<h:dataTable id="tbl" var="car" value="#{bean.cars}">
    <h:column>
        <f:facet name="header">
            <h:outputText value="Model" />
        </facet>
        <h:outputText value="#{car.model}" />
    </h:column>

   //more columns

</h:dataTable>

Export as Excel

    <h:commandButton value="Excel Export">
        <opt:exportActionListener type="xls" target="tbl" fileName="cars"/>
    </h:commandButton>

Export as PDF

    <h:commandButton value="PDF Export">
        <opt:exportActionListener type="pdf" target="tbl" fileName="cars"/>
    </h:commandButton>

Export as CSV

    <h:commandLink value="CSV Export">
        <opt:exportActionListener type="csv" target="tbl" fileName="cars"/>
    </h:commandLink>

Export as XML

    <h:commandLink value="XML Export">
        <opt:exportActionListener type="xml" target="tbl" fileName="cars"/>
    </h:commandLink>

Exclude Columns

Sometime a column may contain delete, detail buttons, checkboxes and other stuff. In such cases these columns need to be ignored
in export process. excludeColumns attribute takes the column indexes to exlude.

    <h:commandButton value="Excel Export">
        <opt:exportActionListener type="xls" target="tbl" fileName="cars" excludeColumns="0,1"/>
    </h:commandButton>

Online Demo

To see exporter in action, checkout the online demo of PrimeFaces.

Update: exportActionListener joined to PrimeFaces UI from Optimus and will be available as a p:dataExporter component in 0.9.0. Note that exportActionListener will not be available in optimus-0.7.3.

One Response to Export JSF Datatable as Excel, PDF, CSV, XML

%d bloggers like this: