Background color issues

Hello, I’m trying to use the cell.getDisplayStyle().getBackgroundColor method, but I’m not getting the correct return value.


I set the background color to Yellow in a particular cell, and this is the object returned:
{
a: -1,
r: -1,
b: -1,
g: -1,
empty: false
}

Is there something I’m misunderstanding?

Hi,


Thanks for your posting and using Aspose.Cells.

In order to get fill color of the cell, you must use foreground color of the cell not the background color of the cell. Please see the following sample code, its source excel file and its console output for your reference. I have tested the code with the latest version: Aspose.Cells for Java v16.10.6.

Please also read the comments inside the code for more help.

Java
Workbook wb = new Workbook(dirPath + “sample.xlsx”);

Worksheet ws = wb.getWorksheets().get(0);

Cell a1 = ws.getCells().get(“A1”);

Style st = null;
//Normally, GetStyle() is used but it does not work with conditional formatting
//st = a1.GetStyle();

//This also works with <span style=“font-family: “Courier New”; font-size: small;”>conditional formatting
st = a1.getDisplayStyle();

if(st.getPattern() == BackgroundType.SOLID)
{
//You must access cell fill color via foreground color property and not via background color property
Color clr = st.getForegroundColor();

System.out.println(clr);
}

C#
Workbook wb = new Workbook(“sample.xlsx”);

Worksheet ws = wb.Worksheets[0];

Cell a1 = ws.Cells[“A1”];

Style st = null;
//Normally, GetStyle() is used but it does not work for conditional formatting
//st = a1.GetStyle();

//This also works with conditional formatting
st = a1.GetDisplayStyle();

if(st.Pattern == BackgroundType.Solid)
{
//You must access cell fill color via foreground color property and not via background color property
Color clr = st.ForegroundColor;

Console.WriteLine(clr);
}

Console Output - Java
com.aspose.cells.Color@ffff00

Console Output - C#
Color [A=0, R=255, G=255, B=0]

Thanks! For some reason, the object returned with “getForegroundColor” is:

{
a: 0,
r: -1,
b: -1,
g: 0,
empty: false
}

But when I use the “toString” method on this object, I get the correct color hex.

So, problem solved. Thanks again!

Hi,


Thanks for your posting and using Aspose.Cells.

Color.getR() and similar methods return byte which is 8-bits long. So the bits are from 0-7 and the 7th bit is used for sign. If it is 0, then the byte value is positive and if it is 1, then the byte value will be negative. 255 makes all the bits from 0-7 as 1, so the value of byte becomes -1.

Please check the following sample code. It prints the value of byte b which is -1 as 255. In short, whenever you get -1, you take it as 255.

Java
byte b = -1;
int c = b & 0xFF;

System.out.println©;

Console Output
255