demir5334
demir5334

Reputation: 225

How to set font color rgb in excel via apache poi

I want to set font color in my project but I can't do it with RGB codes. I'm using this codes for now but I need to do it with RGB codes.

    Workbook wb = new HSSFWorkbook();  
    Sheet sheet = wb.createSheet("Sheet");  
    CreationHelper helper3 = wb.getCreationHelper();
    Font font = wb.createFont();
    font.setColor(IndexedColors.BLUE.getIndex());

How can I set the font color with RGB codes? I looked some questions but I didn't make it.

Upvotes: 4

Views: 10320

Answers (1)

Axel Richter
Axel Richter

Reputation: 61945

Using XSSF one can set font color using XSSFColor. And XSSFColor can be crreated from custom RGB values.

But as you are using HSSF, this is not possible. In HSSF colors always needs to be palette colors. So if a custom color is needed, one of the other HSSFPalette colors needs to be overwritten.

Complete example which works for both, XSSF als well as HSSF. For HSSF it overwrites HSSFColor.HSSFColorPredefined.LIME with RGB 222, 111, 222.

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

public class CreateExcelFontCustomColor {

 public static void main(String[] args) throws Exception {

  byte[] rgb = new byte[]{(byte)222, (byte)111, (byte)222};

  Workbook workbook = new HSSFWorkbook(); String filePath = "./Excel.xls";
  //Workbook workbook = new XSSFWorkbook(); String filePath = "./Excel.xlsx";

  Font font = workbook.createFont();
  if (font instanceof XSSFFont) {
   XSSFFont xssfFont = (XSSFFont)font;
   xssfFont.setColor(new XSSFColor(rgb, null));
  } else if (font instanceof HSSFFont) {
   font.setColor(HSSFColor.HSSFColorPredefined.LIME.getIndex());
   HSSFWorkbook hssfworkbook = (HSSFWorkbook)workbook;
   HSSFPalette palette = hssfworkbook.getCustomPalette();
   palette.setColorAtIndex(HSSFColor.HSSFColorPredefined.LIME.getIndex(), rgb[0], rgb[1], rgb[2]);
  }
  font.setFontHeightInPoints((short)30);
  font.setBold(true);

  CellStyle cellStyle = workbook.createCellStyle();
  cellStyle.setFont(font);

  Sheet sheet = workbook.createSheet();
  Cell cell = sheet.createRow(0).createCell(0);
  cell.setCellStyle(cellStyle);
  cell.setCellValue("test");

  FileOutputStream out = new FileOutputStream(filePath);
  workbook.write(out);
  out.close();
  workbook.close();

 }

}

Upvotes: 7

Related Questions