Apache POI & colors

2019-05-25 07:05发布

问题:

I've some problems with Apache POI, some help would be nice!!

I would like to remove the colors in a subpart of an Excel sheet. To do so, the first thing I tried is to render the cells I want to clean (let say the one of the first row only) and to set their color to white:

cell.getCellStyle().setFillForegroundColor(IndexedColors.WHITE.index);

But if i do that, the color of some cells that are not rendered (let say the one of the second row) are also changed to white cells. It's strange, because the cells that are changed do not have the same foreground color, so I thought they would have different styles ...

Therefore, I've tried another way:

CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.WHITE.index);
cell.setCellStyle(style);

The idea, is to avoid changing a style that may be common to different cells in the Excel sheet. Actually, it solves the color problem, but if I do that, I loose the different styles in the Excel sheet, while I only want to remove some colors...

I'm using a generic Workbook, and I'm reading a xlsx (same problem with a xls) Do you know how to do it ? Thx a lot, regards,

回答1:

If you want to remove the colors, then probably it makes sense to change the fill pattern to NO_FILL rather than setting the color to white as follows:

style.setFillPattern(CellStyle.NO_FILL)

Back to your main question, you've got 2 options of dealing with the cell style amendment:

  • By modifying style viaCellUtil.setCellStyleProperty method

CellUtil.setCellStyleProperty(cell, workbook, CellUtil.FILL_PATTERN, CellStyle.NO_FILL)

  • By cloning styles from the existing style and modifying the property

The example code shown below:

 CellStyle oldStyle = cell.getCellStyle();
 CellStyle newStyle = workbook.createCellStyle();
 newStyle.cloneStyleFrom(oldStyle);
 newStyle.setFillPattern(CellStyle.NO_FILL);
 cell.setCellStyle(newStyle);

However in the 2nd case you're going to create a new cell style for every cell and you might probably consider reusing some of the already updated cell styles and implementing some kind of caching (as otherwise it might lead to performance issues and reaching allowed styles limit).