简体   繁体   中英

Apache POI Wrong Cells Font Being Set

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.

大标签

遗失边界

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM