I am using Apache POI to read .xlsx file. I want to retrieve the Hexadecimal code of the cell background color. I can see the function to print rgb values but I am looking for Hex code.
Workbook workbook = WorkbookFactory.create(new FileInputStream (new File(SAMPLE_XLSX_FILE_PATH)));
Sheet sheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
for (Row row: sheet) {
for(Cell cell: row) {
String cellValue = dataFormatter.formatCellValue(cell);
XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
XSSFColor cellColor = cellStyle.getFillForegroundXSSFColor();
if(cellValue.equals("sh")){
System.out.print(cellValue + "\t");
System.out.println(" cellColor 0: " + cellColor.getRgb()[0]);
System.out.println(" cellColor 1: " + cellColor.getRgb()[1]);
System.out.println(" cellColor 2: " + cellColor.getRgb()[2]);
}
}
Update: 1
As suggested by @Zardo:
if(cellValue.equals("sh")){
System.out.print(cellValue + "\n");
System.out.println(" cellColor 0: " + cellColor.getRgb()[0]);
System.out.println(" cellColor 1: " + cellColor.getRgb()[1]);
System.out.println(" cellColor 2: " + cellColor.getRgb()[2]);
String hex = String.format("#%02x%02x%02x", cellColor.getRgb()[0],cellColor.getRgb()[1], cellColor.getRgb()[2]);
System.out.println(hex.toUpperCase());
}
Output is:
sh
cellColor 0: -1
cellColor 1: -52
cellColor 2: -1
#FFCCFF
I do not think its giving correct color info.