Search code examples
javaswingjtableapache-poitablecellrenderer

Export JTable with custom TableCellRenderer


I have a JTable that uses a TableCellRenderer to colour the background of some cells according to their values.

I need to export this table in an excel file with the same cell formatting. Here is an extract of what I currently see in the JTable.

enter image description here

Do I have to replicate all the logic behind the renderer in Apache POI to get the same result, or there is a quicker way?


Solution

  • You still need to create a workbook, a worksheet, rows and then cells.

    Iterate through your model for each row, and create row and cells ( based on number of columns ).

    Set cell's value based on your table's data.

    For color :

    It will help if your JTable's model has not just the values for each cell, but also its back ground color. If not, you could get background color from the JTable given the values for row, column. You need to apply a cellstyle for each cell ( cell styles can be created independent of number of cells ) and set background color using setFillBackgroundColor().