How to Set Background and Font Color in XLSX Using POI in Java
April 23, 2014
In this page we will learn how to set color in our XLSX. Generally we need to set background color and font color for our rows and cell in excel file. Setting color can be used as heading or column name that increases the readability of excel file. In this example we will understand from scratch how to color in XLSX. All we need is to get an instance of CellStyle and then set the desired color to CellStyle and then assign it to XLSX cell. Create a XSSFWorkbook. Get CellStyle from XSSFWorkbook as below.
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.GREEN.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND);
Font font = workbook.createFont(); font.setColor(IndexedColors.RED.getIndex()); style.setFont(font);
Complete Example
Now we are all set with CellStyle instance that will be used while creating or updating cell. In our example we will create a row with two cell and set the CellStyle. Find the example.ColorXLSX.java
package com.concretepage.poi; import java.io.File; 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.Font; 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.XSSFWorkbook; public class ColorXLSX { public static void main(String[] args) throws IOException { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Color Test"); Row row = sheet.createRow(0); CellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(IndexedColors.GREEN.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); Font font = workbook.createFont(); font.setColor(IndexedColors.RED.getIndex()); style.setFont(font); Cell cell1 = row.createCell(0); cell1.setCellValue("ID"); cell1.setCellStyle(style); Cell cell2 = row.createCell(1); cell2.setCellValue("NAME"); cell2.setCellStyle(style); FileOutputStream fos =new FileOutputStream(new File("D:/xlsx/cp.xlsx")); workbook.write(fos); fos.close(); System.out.println("Done"); } }
