I am trying to create a gradient pattern in a column with each cell having its rgb value. The problem that I am facing is that the rgb color is being overwritten in other cells of that column. So the last generated rgb color is being given to all the cells in the column. I tried creating new objects in the loop for each iteration but the overwriting still persists.
public static void giveGradientToColumn(HSSFWorkbook workbook, HSSFSheet sheet, String yemi, Double minimum, Double maximum) throws IOException {
int columnIndex = 5;
int maxRows = sheet.getPhysicalNumberOfRows();
Random rand = new Random();
int i = maxRows+1;
for(int rowIndex = maxRows-1 ; rowIndex > 0 ; rowIndex--){
Row row = CellUtil.getRow(rowIndex, sheet);
Cell cell = CellUtil.getCell(row, columnIndex);
String cellContent = cell.toString();
String percentvalue = cellContent.split("%")[0];
if(!(percentvalue.equals("NaN")))
{
FileOutputStream fileOut = new FileOutputStream(yemi);
double value;
HSSFWorkbook workbook1 = workbook;
try{
value = Double.parseDouble(percentvalue);
}
catch(Exception e){
continue;
}
double ratio;
if(maximum!=minimum)
ratio = 2 * (value-minimum) / (maximum - minimum);
else
ratio = 1;
int b = (max(0, 255*(1 - ratio)));
int r = (max(0, 255*(ratio - 1)));
int g = 255 - b - r;
r = rand.nextInt(255);
g = rand.nextInt(255);
b = rand.nextInt(255);
System.out.println(r+" "+g+" "+b);
HSSFCellStyle style = workbook1.createCellStyle();
HSSFPalette palette = workbook1.getCustomPalette();
HSSFColor myColor = setColor(workbook1, (byte) r, (byte) g, (byte) b);
short palIndex = myColor.getIndex();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(palIndex);
cell.setCellStyle(style);
workbook1.write(fileOut);
fileOut.close();
}
}
}
@SuppressWarnings("deprecation")
public static HSSFColor setColor(HSSFWorkbook workbook, 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(HSSFColor.GOLD.index, r, g, b);
hssfColor = palette.getColor(HSSFColor.GOLD.index);
}
} catch (Exception e) {
System.out.println(e);
}
return hssfColor;
}
I am printing the rgb values for debugging and the last printed color value is being given to all the cells in the column. (rgb currently is calculated as random.)
Output:-
Output Image
Where am I going wrong?