Search code examples
jsfdatatableexportapache-poiopenfaces

How to export an OpenFaces DataTable in Excel/CSV Format?


Unfortunately, OpenFaces Datatable has not yet an export capability unlike Primefaces or IceFaces. While Exporting is a piece of cake, filtering an IceFaces or primefaces datatable is less easy, Yet primeFaces's filtering does not work with JSF DataModel (sad but true).

Using OpenFaces DataTable filtering is a piece of cake and so handy and powerful. But how about The end user who wants to export a datatable that s/he filtered, to a format like CSV or MS Excel.

The great Dmitry from OpenFaces, gave me a hint : Use OpenFaces DataTable method: getDisplayedRowDatas() that will grab the currently displayed rows from a datatable, then use some thrid library like Itext to export in PDF for example.

In my head, this should go this way:

  • Create a backing bean for this purpose.
  • Add Apache POI third library to the classpath
  • Write code using Apache POI to export the content of the OpenFaces datatable with its method getDisplayedRowsDatas() - but I am afraid this method does not return the names of columns' headers - or grab the HTML table rendered by an OpenFaces Datatable as a buffered string and use Apache POI to produce an Excel file streamed with the Buffer.

In the MyFaces example I came across recently: MyFaces Datatable Export Example, the developer uses Myfaces component <t:buffer value=#{myExportBean.myBufferString}> datatable here </t:buffer /> to transform the content of the datatable to a buffered String which makes things easier. JSF Core does not have such component unfortunately.

Did someone come across this before? Help or better alternatives are much appreciated.


Solution

  • You can check out the experimental DataTable export API, which is available in the current nightly build. We'll declare this API officially if it stands the test of time. For now, only CSV export is available, but you can write your own exporters for other formats. Here's the code that you should put in your action handler to make it work:

    DataTable myTable = Faces.component("form:myTable", DataTable.class);
    myTable.export(new CSVTableExporter());
    

    It exports the data for all of the rows and columns as currently displayed by the table (only the current page of a paginated table is exported currently).