Setting background custom color, XSSFWorkbook

I use this code to change the font in excel to color, which I define

        Color sColor = new Color (value,0,0);
        XSSFColor userColor = new XSSFColor(sColor);

        CellStyle style = wb.createCellStyle();
        XSSFFont font = wb.createFont();

        font.setColor(userColor);
        style.setFont(font);
        cell.setCellStyle(style);

Can I change the cell's Background same way.

I saw the question here Setting background custom color not working for XSSF in Apache POI but I had error on

 ((XSSFCellStyle)cellStyle).setFillForegroundColor(color);

1 answer

  • answered 2018-11-07 21:00 Centos

    Create cell style object:

    CellStyle backgroundStyle = workbook.createCellStyle(); 
    

    Set custom color:

    backgroundStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
    

    Add style to the cell:

    cell.setCellStyle(backgroundStyle);