How to set the background color of a cell in Excel Sheet Using Apache POI

How to set the background color of a cell in Excel Sheet Using Java

The following code shows how to set the background color of a cell in Excel Sheet Using Java

package pack1;

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * Fills and Colors
 */
public class FillsAndColors {
    public static void main(String[] args) throws IOException {
        try (Workbook wb = new XSSFWorkbook()) { 
            Sheet sheet = wb.createSheet("new sheet");

            // Create a row and put some cells in it. Rows are 0 based.
            Row row = sheet.createRow(1);

            // Aqua background
            CellStyle style = wb.createCellStyle();
            style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
            style.setFillPattern(FillPatternType.BIG_SPOTS);
            Cell cell = row.createCell(1);
            cell.setCellValue(new XSSFRichTextString("SuJoy"));
            cell.setCellStyle(style);

            // Orange "foreground", foreground being the fill foreground not the font color.
            style = wb.createCellStyle();
            style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            cell = row.createCell(2);
            cell.setCellValue(new XSSFRichTextString("SuJoy"));
            cell.setCellStyle(style);

            // Write the output to a file
            try (FileOutputStream fileOut = new FileOutputStream("D:\\MyExcel.xlsx")) {
                wb.write(fileOut);
            }
        }
    }
}

OUTPUT:

The only business I know is learning new technology and spreading the knowledge. I believe sharing is learning. This is my prime reason to build this site.
I welcome and value your comments, suggestions and corrections.

1592total visits,1visits today

The only business I know is learning new technology and spreading the knowledge. I believe sharing is learning. This is my prime reason to build this site. I welcome and value your comments, suggestions and corrections.