I'm using Apache POI to read data in a spreadsheet of part numbers. I look up the part number in our database, if we have a CAD drawing of the part I color the part number cell green, if we don't I color it red. After the processing is done the spreadsheet is saved. The problem I'm having is that every cell in that column comes out green. I've stepped through the code, the logic to look up the part number is working fine and the logic to determine what color the cell should be and setting the color and fill appears to work as well. Any ideas what I'm doing wrong here?
Thanks.
//Check the parts
for(int r=1;r<sheet.getPhysicalNumberOfRows();r++) {
String partNumber = null;
switch(cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:
long pNum = (long) cell.getNumericCellValue();
partNumber = String.valueOf(pNum);
break;
case HSSFCell.CELL_TYPE_STRING:
partNumber = cell.getStringCellValue();
break;
default:
logger.info("Part Number at row " + r + " on sheet " + partList.getSheetName(s) + "is of an unsupported type");
}
try {
List<String> oldMaterialNumbers = getOldMaterialNumbers(partNumber);
boolean gotDrawing = checkPartNumber(oldMaterialNumbers, partNumber);
//If there's a drawing then color the row green, if not red.
short bgColorIndex = gotDrawing
?HSSFColor.LIGHT_GREEN.index //42
:HSSFColor.RED.index; //10
HSSFCell curCell = row.getCell(partNumberColumn);
HSSFCellStyle curStyle = curCell.getCellStyle();
curStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
curStyle.setFillForegroundColor(bgColorIndex);
curCell.setCellStyle(curStyle);
}catch(Exception e) {
throw e;
}
}
Short version: Create styles only once, use them everywhere.
Long version: use a method to create the styles you need (beware of the limit on the amount of styles).
you can also use methods to do repetitive tasks while creating styles hashmap
then, in your "main" code, set the style from the styles map you have.
checkout the example here
http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java
For apache POI 3.9 you can use the code bellow:
The methods for 3.9 version accept short and you should pay attention to the inputs.
To create your cell styles see: http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors.
Custom colors
HSSF:
XSSF:
I believe it is because
cell.getCellStyle
initially returns the default cell style which you then change.Create styles like this and apply them to cells:
Although as the previous poster noted try and create styles and reuse them.
There is also some utility class in the XSSF library that will avoid the code I have provided and automatically try and reuse styles. Can't remember the class 0ff hand.