0
votes

I am having an issue with Apache POI in that when I set a font to a style, then set that style to a cell, it will correctly apply that font to the cell I want, but will also apply that font to other cells. For example, I am creating an HSSF excel workbook from a template file I have set up. This template file has cells already filled in that will always be then same, and when I fill in the cells I want and change their font size, some of the pre-filled cells font sizes also change. However, this only happens if I don't create a new HSSFCellStyle. The problem with that is if I do just create a new CellStyle, I lose formatting I have preset for the cells I want to fill. This might be easier to explain with some examples and code. So here are the two different outputs I can get.

BigLabels

MissingBorders

In the first picture you can see that "2400 Hr Clock" has been resized, even though in my code, I never apply the style to that cell, it only(should only) gets applied to the date cell and the time cell. This is when I set the style like this:

HSSFCellStyle dataStyle = cell.getCellStyle();
dataStyle.setFont(font);

But when I set the style like this instead:

HSSFCellStyle dataStyle = currentWorkbook.createCellStyle();
dataStyle.setFont(font);

I get what's in the second picture, but I lose previous formatting like the borders on the first parts of the cells. Note that the reason I didn't lose all of the border is because the cells are multiple cells merged together, but you can see part of the border is missing, but the "2400 Hr Clock" has not been resized. I am not sure what is causing this and I am not sure what to try next. The font is created like this:

HSSFFont font = currentWorkbook.createFont();
font.setFontName("Times");
font.setFontHeightInPoints(fontSize);
1
"The problem with that is if I do just create a new CellStyle, I lose formatting I have preset for the cells I want to fill." - I think that is how it works, yes, since that's how the Excel file format works I think. Hopefully there's a 'clone cell style' you can use instead, but I don't remember one.Rup
Aha. That seems to be the solution. Thank you! Just cloned from the old cell.Randy_E

1 Answers

2
votes

The solution is to clone the style, instead of get the style like this:

HSSFCellStyle dataStyle = currentWorkbook.createCellStyle();
dataStyle.cloneStyleFrom(cell.getCellStyle());
dataStyle.setFont(font);