、先說設定單元格的背景顔色:
HSSFWorkbook wb = new HSSFWorkbook();
...
HSSFCellStyle style = wb.createCellStyle();
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.WHITE.index);
cell.setCellStyle(style); //cell 是 HSSFCell 對象
setFillPattern是設定單元格填充樣式,SOLID_FOREGROUND純色使用前景顔色填充,接着設定前景顔色(setFillForegroundColor)就可以給單元格着色了。setFillForegroundColor()方法的參數是一個short類型,POI使用索引來代表顔色,預設已經有一些顔色了,如:
8: BLACK
60: BROWN
59: OLIVE_GREEN
58: DARK_GREEN
...
顔色的索引還必須是 0x08 ~ 0x40 (8 ~ 64) 的數字。
二、接下來,使用自定義顔色
如果不使用POI提供的預設顔色,就需要自定顔色索引:
HSSFPalette palette = wb.getCustomPalette(); //wb HSSFWorkbook對象
palette.setColorAtIndex((short) 9, (byte) (color.getRed()), (byte) (color.getGreen()), (byte) (color.getBlue()));
然後使用顔色,如上例,可以用新的顔色索引,替換原有的顔色:
style.setFillForegroundColor((short) 9);
三、setFillPattern(),設定單元格填充的樣式,比如:
style.setFillPattern(HSSFCellStyle.BIG_SPOTS);
style.setFillForegroundColor(HSSFColor.RED.index);
style.setFillBackgroundColor(HSSFColor.LIGHT_BLUE.index);
這樣目前單元格就被紅藍交替的格子填充

上面3行代碼,去掉setFillPattern設定填充樣式的一行,同時設定前景色和背景色,生成的檔案沒有填充顔色,此時既不會用前景色填充,也不會用背景色填充。這種情況與 setFillPattern(HSSFCellStyle.NO_FILL); 時一樣。
api上setFillBackgroundColor方法說明有如下示例:
public void setFillBackgroundColor(short bg)
-
set the background fill color.
For example:
optionally a Foreground and background fill can be applied: Note: Ensure Foreground color is set prior to backgroundcs.setFillPattern(HSSFCellStyle.FINE_DOTS ); cs.setFillBackgroundColor(new HSSFColor.RED().getIndex()); //上面代碼經測試,是黑色點狀的背景(無前景),設定紅色背景色無效
or, for the special case of SOLID_FILL:cs.setFillPattern(HSSFCellStyle.FINE_DOTS ); cs.setFillForegroundColor(new HSSFColor.BLUE().getIndex()); cs.setFillBackgroundColor(new HSSFColor.RED().getIndex());
It is necessary to set the fill style in order for the color to be shown in the cell.cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND ); cs.setFillForegroundColor(new HSSFColor.RED().getIndex());