Poi 操作excel 定義單元格顏色
阿新 • • 發佈:2019-01-03
使用java操作excel時可以指定單元格的顏色,有兩種方法:
1.使用提供的索引:
//設定樣式-顏色
HSSFCellStyle style = workbook.createCellStyle();
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
HSSFColor.SKY_BLUE.index 這裡的顏色是java提供的2.自定義顏色
比如這裡有一個16進位制的字串用來表示顏色,通過下面的方法來自定義顏色:
String color = "cbfdee"; //此處得到的color為16進位制的字串 //轉為RGB碼 int r = Integer.parseInt((color.substring(0,2)),16); //轉為16進位制 int g = Integer.parseInt((color.substring(2,4)),16); int b = Integer.parseInt((color.substring(4,6)),16); //自定義cell顏色 HSSFPalette palette = workbook.getCustomPalette(); //這裡的9是索引 palette.setColorAtIndex((short)9, (byte) r, (byte) g, (byte) b); HSSFCellStyle style = workbook.createCellStyle(); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setFillForegroundColor((short)9);
然後cell.setCellStyle(style);即可將樣式賦給指定單元格