4
votes

I'm using Apache POI to read an existing template excel file and would like to copy the existing styles in some header rows and apply them to new cells.

It seems like the existing formatting is not being applied (IE, Date, Currency, Percentage etc).

The code is pretty basic:

//read existing style
Row existingRow = sheet.getRow(headerRowIndex);
Cell existingCell = existingRow.getCell(0);
CellStyle currentStyle = existingCell.getCellStyle();


//apply date style here
Date date = StringUtil.toDate(map.get(column.getHeaderName()));
cell.setCellValue(date);
//apply previous style      
cell.setCellStyle(currentStyle);

It does copy the font and background color etc but it seems like the formatting is lost (all cells have "general" formatting applied).

Also when I do this:

currentStyle.getDataFormat(); // always 0

So it makes me think that I'm not reading the formatting correctly. Any ideas on how to accomplish this?

1

1 Answers

2
votes

OK I figured it out, it was my mistake. I was reading the style from the first cell in the row and applying it to all, instead of reading from each cell.

This fixes it

Cell existingCell = existingRow.getCell(i);