Export your dataTable to Excel and PDF using Primefaces

Do you need exporting your Primefaces dataTable to any kind of format such as Excel, PDF, CSV, XML ? In this tutorial which uses Primefaces version 14.0.5 (October 2024) we will show how to do it step-by-step!

Setting up the Primefaces Project

In order to export your dataTable, you can use the DataExporter UICommand which is part of the Primefaces suite. Using it is pretty simple. The required libraries to run this example are:

  • Primefaces library
  • Apache POI library (dependency)
  • iText library  (dependency)

The recommended way to configure your project for a Jakarta EE server (such as WildFly) requires the following dependencies in your pom.xml:

Firstly, create a Web project using Maven with the following dependencies in it:

<dependencies>
    <dependency>
        <groupId>jakarta.platform</groupId>
        <artifactId>jakarta.jakartaee-api</artifactId>
        <version>${jakartaee.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>${primefaces.version}</version>
    </dependency>
</dependencies>

Please note that, if you are developing a Jakarta EE 10 application (using jakarta namespace) then you need to specify the following classifier in your dependency:

<classifier>jakarta</classifier>

Besides, you will need some extra dependencies in order to export your Datatable to PDF or to Excel:

<dependency>
    <groupId>com.github.librepdf</groupId>
    <artifactId>openpdf</artifactId>
    <version>1.3.30</version>
</dependency>
 
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.0</version>
</dependency>

Coding the View

The PrimeFaces component required to export your dataTable is called DataExporter and it is nested in a UICommand component such as commandButton or commandLink. See the following example:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui">

<h:head>
</h:head>

<h:body>
    <h:form id="jsfexample">

        <p:dataTable value="#{manager.cacheList}" var="item" id="mydata">
            <p:column>
                <f:facet name="header">Name</f:facet>
                <h:outputText value="#{item.name}" />
            </p:column>
            <p:column>
                <f:facet name="header">Surname</f:facet>
                <h:outputText value="#{item.surname}" />
            </p:column>
            <p:column>
                <f:facet name="header">Age</f:facet>
                <h:outputText value="#{item.age}" />
            </p:column>
            <p:column>
                <f:facet name="header">City</f:facet>
                <h:outputText value="#{item.city}" />
            </p:column>
        </p:dataTable>
        <p:panel header="Export All Data">
            <h:commandLink>
                <p:graphicImage value="/icons/excel.jpg" />
                <p:dataExporter type="xls" postProcessor="#{manager.postProcessXLS}"
                                target="mydata" fileName="myexcel" pageOnly="true" />
            </h:commandLink>
            <h:commandLink>
                <p:graphicImage value="/icons/pdf.png" />
                <p:dataExporter type="pdf" target="mydata" fileName="mypdf" pageOnly="true" />
            </h:commandLink>

            <h:commandLink>
                <p:graphicImage value="/icons/csv.jpg" />
                <p:dataExporter type="csv" target="mydata" fileName="mycsv" pageOnly="true" />
            </h:commandLink>

            <h:commandLink>
                <p:graphicImage value="/icons/xml.jpg" />
                <p:dataExporter type="xml" target="mydata" fileName="myxml" pageOnly="true" />
            </h:commandLink>
        </p:panel>

    </h:form>
</h:body>
</html>

As you can see this page contains:

    • a datatable with id=”mydata”

    • a panel with icons to export data in Excel, PDF, CSV or XML

The <p:dataExporter> specifies the type of export with the “type” attribute. You can opt between “xls“,”pdf,”csv” and “xml“. Next, you need to select the dataTable with the “target” attribute and the resulting filename with the “fileName” attribute. (In this tutorial we will show just Excel and PDF export, however using csv and xml is trivial, just add the required type attribute to the dataExporter)

Coding the Backing Bean

Next, we will code the Backing Bean which will produce some random Person objects to populate the DataTable.

Additionally an Excel, PDF dataExporter can use the preProcessor or postProcessor to add some pre-processing or post-processing functionalities to your document. This allows you to add custom styles to your document or also to modify the content as well.

@Named(value = "manager")
@ViewScoped
public class PropertyManager implements Serializable {

    private String name;
    private String surname;
    private int age;
    private String city;
 

    @PostConstruct
    public void init() {
        cacheList = generateRandomPeople();
    }

    public void clear() {
        cacheList.clear();
    }

    public List<Person> generateRandomPeople() {
        List<Person> people = new ArrayList<>();
        String[] names = {"Alice", "Bob", "Charlie", "David", "Emma", "Frank", "Grace", "Henry", "Isabel", "Jack"};
        String[] surnames = {"Smith", "Johnson", "Williams", "Brown", "Jones", "Miller", "Davis", "Garcia", "Martinez", "Lee"};
        String[] cities = {"New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio", "San Diego", "Dallas", "San Jose"};

        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            String name = names[random.nextInt(names.length)];
            String surname = surnames[random.nextInt(surnames.length)];
            int age = 18 + random.nextInt(50); // Random age between 18 and 67
            String city = cities[random.nextInt(cities.length)];

            Person person = new Person(name, surname, age, city);
            people.add(person);
        }
        return people;
    }
    public void postProcessXLS(Object document) {
        DataFormatter formatter = new DataFormatter(Locale.US);
        HSSFWorkbook wb = (HSSFWorkbook) document;
        HSSFSheet sheet = wb.getSheetAt(0);
        CellStyle style = wb.createCellStyle();
        style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());

        for (Row row : sheet) {
            for (Cell cell : row) {

                switch (cell.getCellType()) {

                case STRING:
                    cell.setCellValue(cell.getStringCellValue().toUpperCase());
                    cell.setCellStyle(style);
                    break;

                }

            }
        }
    }

    List<Person> cacheList = new ArrayList();

        // getters/setters omitted for brevity 
}

As you can see, within the postProcessXLS we are iterating over the list of Rows and Cells of the Spreadsheet. then, we are checking the Cell type to apply an Uppercase if the Cell contains a String.

Deploying the application

Once that you deploy the application on a Container such as WildFly, you will be able to see the list of Person object in the upper dataTable and the icons to export the data:

export primefaces datatable excel pdf csv

Exporting only the current page

By default dataExporter works on whole dataset, if you’d like export only the data displayed on current page (as we did in our example), set the pageOnly attribute to true.

<p:dataExporter type="xml" target="mydata" fileName="mydata.xml" pageOnly="true" />

Conclusion

In conclusion, this tutorial has equipped you with the essential knowledge to seamlessly export PrimeFaces DataTable content into various file formats, empowering users to efficiently manipulate and share tabular data.

Understanding the step-by-step export process for each file format – Excel, PDF, CSV, and XML – ensures a comprehensive grasp of the mechanisms involved. You’ve gained insights into configuring and utilizing PrimeFaces components, enabling swift and accurate data exportation with minimal effort.

Source code: Jakarta EE 10 version:  https://github.com/fmarchioni/mastertheboss/tree/master/web/primefaces/export-datatable-jakartaee

Source code: Jakarta EE 8 version: https://github.com/fmarchioni/mastertheboss/tree/master/web/primefaces/export-datatable