Let us consider that we have to write a cell in excel and apply custom color for that.
In our example, we will apply some custom grey color,instead of the default grey color options available in Hssf POI.
Lets start by creating the workbook..
Then in ExcelCreator file, we need to write the following methods..
In our example, we will apply some custom grey color,instead of the default grey color options available in Hssf POI.
Lets start by creating the workbook..
// creating work book.. HSSFWorkbook workbook = new HSSFWorkbook(); //defining the cell style CellStyle customGrey = ExcelCreator.customHeaderGreyColor(workbook); // creating the sheet.. HSSFSheet hssfSheet = workbook.createSheet("custom colors"); HSSFRow hssfRow = hssfSheet.createRow(0); // creating the 1st row hssfRow.createCell(0).setCellValue("Welcome HSSF!"); hssfRow.getCell(0).setCellStyle(customGrey ); // applying the cell style to cell
Then in ExcelCreator file, we need to write the following methods..
//method to return the cell style public static CellStyle customHeaderGreyColor(HSSFWorkbook workbook) { HSSFCellStyle headerStyle = workbook.createCellStyle(); headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); headerStyle.setVerticalAlignment(headerStyle.VERTICAL_JUSTIFY); HSSFColor customGrey = getCustomColor(workbook, HSSFColor.GREY_80_PERCENT.index, (byte) 128, (byte) 128, (byte) 128); applyWhiteBorder(headerStyle); /* Applying custom grey color */ headerStyle.setFillForegroundColor(customGrey.getIndex()); headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); return headerStyle; } // method to get custom color public static HSSFColor getCustomColor(HSSFWorkbook workbook, short colorIndex, byte r, byte g, byte b) { HSSFPalette palette = workbook.getCustomPalette(); HSSFColor hssfColor = null; try { hssfColor = palette.findColor(r, g, b); if (hssfColor == null) { palette.setColorAtIndex(colorIndex, r, g, b); hssfColor = palette.getColor(colorIndex); } } catch (Exception e) { } return hssfColor; }