How to apply cell background color using HSSF usin

2019-03-06 01:51发布

问题:

I'm trying to format the cell background color based on the Testcase Execution status like if the test case got passed then the cell background should become Green and text color should be White.

Similarly for Failed test cases cell background color : Red and Text color : White

For that I tried the following script.

Background:

HSSFCellStyle style = wBook.createCellStyle()
style.setFillBackgroundColor(IndexedColors.GREEN.getIndex())

Foreground:

HSSFFont font = wBook.createFont()
font.setColor(HSSFColor.WHITE.index)
style.setFont(font)
resultCell.setCellStyle(style)

But after executing the test cases, cell background is not applying where as foreground only applies.

FYI: I'm Working with Excel version .XLS

Anyone give the correct method to apply background of the cell?

Thanks

回答1:

You are fiddling with the wrong. Excel's cell fills are pattern fills. There fill background color is the color behind the pattern and fill foreground color ist the color of the pattern.

So if setting setFillBackgroundColor, then you are setting the color behind the pattern which will only be visible if the pattern has gaps and is not solid.

Normally a cell is filled using SOLID_FOREGROUND pattern. So the color of the pattern is needed and not the color behind the pattern.

Try

style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);


回答2:

It's working for the below lines:

style.setFillForegroundColor(IndexedColors.GREEN.getIndex())
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND)