ShadyBears
ShadyBears

Reputation: 4175

Unable to read cell color of an xls file using Apache POI

import org.apache.poi.ss.usermodel
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


// Assume this method is wrapped in a class
public static void parseFile(){
    // File Path has a .xls extension
    FileInputStream file = new FileInputStream(filePath);
    HSSFWorkbook wb = new HSSFWorkbook(file);
    HSSFSheet sheet = wb.getSheetAt(0);

    for(int rn = sheet.getFirstRowNum(); rn <= sheet.getLastRowNum(); rn++){
        HSSFRow row = sheet.getRow(rn);

        for(int cn = 0; cn < row.getLastCellNum(); cn++){
            HSSFCell cell = row.getCell(cn);
            //This is apache's color
            HSSFColor color = cell.getCellStyle().getFillBackgroundColorColor; 

            // Excel entire row is red and it is not entering here.
            if(color.equals(IndexedColors.RED)){
                System.out.println("I made it here!");
                cn++;
                continue;
            }
        }
    }
}

The file is processing fine but it won't enter my "if statement". Am I doing it wrong? Can this be done with xls files? I see examples for xlsx but I don't see any for xls. Thanks!

Upvotes: 0

Views: 550

Answers (1)

knuti
knuti

Reputation: 9

The method getFillBackgroundColorColor() returns the following type :

org.apache.poi.ss.usermodel.Color

not a

java.awt.Color

one way to check for RED is checking the RGB values, like so:

byte[] rgb=colore.getRGB();
System.out.println("color" + " " + rgb[0] + " " + rgb[1] + " " + rgb[2] );
if ( (rgb[0] == (byte)0xff) 
  && (rgb[1] == 0)
  && (rgb[2] == 0)) {
     System.out.println("that is totally red");
}

the main point is, do not mix up class Color of apachePOI with java.awt.Color

Upvotes: 1

Related Questions