Monday, March 12, 2012

Create Apache POI Custom Color


Excel template path
String excelTemplate = "C:/Export-Generic.xls";

Create HSSFWorkbook
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(excelTemplate));

Create HSSFPalette (Represents a workbook color palette.)
HSSFPalette palette = workbook.getCustomPalette();

Sets the color at the given offset
Parameters:
index the palette index, between 0x8 to 0x40 inclusive
red the RGB red component, between 0 and 255 inclusive
green the RGB green component, between 0 and 255 inclusive
blue the RGB blue component, between 0 and 255 inclusive
Note: As I know of default colors occupy 0-40. Therefor, custom colors needs start at 41. Custom color that I've chosen is #CADDFF it's RGB values are R = 202, G = 221, and B = 255. http://html-color-codes.info helped me to get the RGB colors.

palette.setColorAtIndex(new Byte((byte) 41), new Byte((byte) 202), new Byte((byte) 221), new Byte((byte) 255));


Now we have custom color palette. We can use this to set our style.
Create style
HSSFCellStyle style = workbook.createCellStyle();

Apply the our custom color to cell background
style.setFillForegroundColor(palette.getColor(41).getIndex());


Happy Coding :-)

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home