The cell cannot set the background color

public class ColorsAndBackground {
public static void main(String[] args) throws Exception {
String dataDir = “D://test//”;
// Instantiating a Workbook object
Workbook workbook = new Workbook();

	Worksheet worksheet = workbook.getWorksheets().get(0);
	Cells cells = worksheet.getCells();

	// Accessing the "A1" cell from the worksheet
	Cell cell = cells.get("A1");
	Style style = cell.getStyle();

	// Setting the foreground color to yellow
	style.setBackgroundColor(Color.getYellow());

	// Saving the modified style to the "A1" cell.
	cell.setStyle(style);

	// Saving the Excel file
	workbook.save(dataDir + "ColorsAndBackground_out.xls");
}

image.png (29.2 KB)

Cannot get the correctly background color for the cell.

image.png (16.7 KB)
image.png (41.9 KB)

@huawei,

Thanks for the code segment and screenshots.

Please use ForegroundColor attribute instead of BackgroundColor property to set the cell’s shading/fill color for your needs, see the updated code segment for your reference:
e.g
Sample code:

String dataDir1 = "f:\\files\\";
					// Instantiating a Workbook object
					Workbook workbook = new Workbook();

						Worksheet worksheet = workbook.getWorksheets().get(0);
						Cells cells = worksheet.getCells();

						// Accessing the "A1" cell from the worksheet
						Cell cell = cells.get("A1");
						Style style = cell.getStyle();

						// Setting the foreground color to yellow
						style.setForegroundColor(Color.getYellow());
						style.setPattern(BackgroundType.SOLID);
						
						// Saving the modified style to the "A1" cell.
						cell.setStyle(style);
						

						// Saving the Excel file
						workbook.save(dataDir1 + "ColorsAndBackground_out1.xls");

Moreover, if you want to get the fill color of cell, please use the getForegroundColor() method instead of getBackgroundColor() method.

Please see the following sample code for your reference:
e.g
Sample code:

[Java]
Cell cell = …

Style st = cell.getStyle();

if(st.getPattern() == BackgroundType.SOLID)
{
    //Now check the foreground color property
    Color clr = st.getForegroundColor();
}

Moreover, see the document with notes for your reference on cells’ formattings:

Ok, thanks for your reply.

@huawei,

You are welcome.