Search code examples
javaexcelapache-poibackground-colorxssf

Java Apache POI - XSSFCell setFillBackgroundColor Has No Effect


I have looked all over stack overflow and could not seem to get my java code to fill the background color of an XSSF excel cell. From what others have said, this should make the top left corner cell yellow:

// Example Code
try {

    // prepare
    FileInputStream resource = new FileInputStream( FILEPATH + FILENAME );
    XSSFWorkbook workbook = new XSSFWorkbook( resource );
    XSSFSheet sheet = workbook.createSheet( "Example Sheet" );

    // create
    XSSFRow row = sheet.createRow( 0 );
    XSSFCell cell = row.createCell( 0 );
    XSSFCellStyle style = workbook.createCellStyle();
    XSSFColor color = new XSSFColor( Color.YELLOW );

    // stylize
    style.setFillBackgroundColor( color );
    cell.setCellStyle( style );

    // finalize
    FileOutputStream output = new FileOutputStream( "Example Workbook.xlsx" );
    workbook.write( output );
    workbook.close();

} catch ( Exception e ) {

    // error
    e.printStackTrace();

}

...but it doesn't. Can someone let me know what I am doing wrong? I am using Apache POI version 3.16 by the way.

Thanks!


Solution

  • Three properties of CellStyle determine how a cell is filled:

    • FillPattern
    • FillForegroundColor
    • FillBackgroundColor

    Most fill patterns like FillPatternType.BIG_SPOTS use both colours. The name FillForegroundColor is misleading, but understandable. It's the foreground colour of the fill pattern which is still in the background of the cell.

    To fill a cell with one colour, you need to use FillPatternType.SOLID_FOREGROUND which uses the foreground colour. So you need to change your code as follows:

    // stylize
    style.setFillForegroundColor(color);
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    cell.setCellStyle(style);