Wednesday 15 August 2012

Creating Excel files using NPOI - Getting a cell's co-ordinates by ICell

The greatest thing about exporting data to Excel is the ability to create formulae that will do a lot of the user's hard work for them later on.

I've been working with the .NET port of Java's POI called NPOI to allow me to create a quite complicated spreadsheet from scratch, and I've noticed that there are quite a few holes in the library that (unless I'm mistaken and the functionality exists) need to be filled.

My next few blog posts will probably be spent documenting some of this functionality, and I'm going to start with getting a cell reference by the cell object itself. For the purposes of this blog post, I'm going to refer to the co-ordinates of a cell "A1, B2, C3" as a cell reference.

I couldn't find a way in NPOI to allow me to get a cell reference from a cell. I found that I had to piece this information together myself, and I used the CellReference class to do it. Once I had the elements, I just joined them together.

This function is particularly useful to me, because while I'm iterating through a loop for a collection of data, I can grab the cell reference as soon as I create a cell, and keep a note of it to create subtotals and totals farther down the line. You may want to wrap some error trapping around this code and catch the right exceptions.