Getting hex color from excel cell

This days I troubled with APACHE POI lib how to extract background color from excel cell.
The problem is that POI lib has object HSSFColor witch has own palette of colors, so you need to get from workbook custom pallet of colors then get RGB values then get you can get HEX color.
The same way you can get Foreground fill color, you need just instead calling method getFillBackgroundColor() call getFillForegroundColor().

public static String extractBackgroundColor(HSSFCell p_cell, HSSFWorkbook Workbook) {
        // get custom pallet of colors from excel file
       HSSFPalette hsfPallet = Workbook.getCustomPalette();
        // get key of that custom pallet       
        short key =  p_cell.getCellStyle().getFillBackgroundColor();
      // creating object HSSFColor  from key
        HSSFColor color = hsfPallet.getColor(key);
      // getting rgb values
        short[] rgb = color.getTriplet();
      // creating java.awt.Color object, you need that object for method Integer.toHexString()
         Color c = new Color(rgb[0], rgb[1], rgb[2]);
      // and finnaly
        String hex = Integer.toHexString(c.getRGB());
        return  hex.substring(2,hex.length());


  1. How can I do it using XSSF?
    I don't see any XSSF related ColorPalette object associated.

  2. Try working on the same line with XSSF...


Post a Comment

Popular Posts