Declarative Approach (using Export Collection Action Listener):
The first method is a declarative approach to achieving the export to excel functionality, however, as this is a declarative approach, this approach has its limitations, some of which I will be mentioning following the implementation. This is a pretty quick way of achieving the export functionality.
Below is the code I have for the export using the Export Collection Action Listener:
As you can see, it is pretty self straightforward to implement the export to excel functionality. We have a button which has the exportCollectionActionListener under it. Now, about the limitations for this approach that I briefly mentioned above, there are a few (may be more). Below are a couple that I can think of on the top of my head:
1. Data can be exported from a table, tree or tree table only. Well, what if you do not have any of these in the page? (for example, you could have an iterator, DVT component). I guess you are out of luck then (just kidding, go to approach #2)
2. What if you want to add styling to the exported excel?
There are a few other scenarios where you this approach may not be suitable for you (also depending on the version that you are on)Programmatic Approach (using File Download Action Listener and Apache POI):
There may be other ways, other than Apache POI, but since Apache POI seem very popular and is open API for generating Microsoft documents (in this case Excel) in Java, I will be using this approach.
Below is a source snippet from the jspx page for this approach:
As you see in the properties of the fileDownloadActionListener, I have specified the file extension as .xlsx. This can be achieved using the XSSF implementation in Apache POI which is used in the EmployeeBean's exportToExcel method as below:
This method gives you a pretty good control if you want to tweak or skip some rows or if you want to style the cell, etc.
That is it for this post, if you have any comments or question please go ahead and comment on this post.