January 07, 2009 | Category: Uncategorized

Neater Excel in Java

If you write applications or websites using Java, you’ve probably needed to export some data to Excel at some point or other. It’s pretty well accepted that the best library for this is the invaluable POI. It provides a neat wrapper over most Excel functionality. It lets you create or reference a spreadsheet (an HSSFWorkbook in POI terms), and then gives you object abstractations for just about any way you might want to manipulate that. Cell styles, formulas, drawing shapes… I won’t go into everything but the cook book is a pretty good starting point for any work you might be doing.

The one thing that’s always bothered me about POI is that it’s pretty low-level, you have to manage absolutely every aspect of what you’re doing. Now it’s great to be able to access that kind of power, but an abstraction over the top would be good.

That’s where jXLS comes in. It builds on top of POI to provide a templating approach to writing new Excel documents, a decent abstraction for most purposes.

Rather than managing everything from what can quickly become fairly complex Java code, you create a template excel file that contains placeholders for where your data should appear. It’s smart enough to be able to intelligently expand a collection of beans and create a new row for each one. That can reduce your boilerplate code significantly.

Downsides? The documentation isn’t the best, and the expression language for some of the more advanced uses is JEXL, which is pretty horrible. Those, however, aren’t major concerns. You’ll rarely need either in depth and, if in doubt, you can always drop down to the POI APIs anyway.

Now, it’s not to be used in all circumstances, there are still situations that are a little beyond it, but it’s an extremely good 80/20 API (you get 80% of the use cases made easy, and the other 20% are still possible). Definitely worth a look.