如何通过Apache POI在Excel中设置字体颜色RGB

3

我想在我的项目中设置字体颜色,但是我不能使用RGB代码。目前我正在使用这些代码,但我需要用RGB代码来实现。

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

我该如何使用RGB代码设置字体颜色? 我查看了一些问题,但是没有成功。

1个回答

6
使用 XSSF,可以使用 XSSFColor 设置字体颜色,并且可以从自定义的 RGB 值创建 XSSFColor
但是,如果你正在使用 HSSF,这是不可能的。在 HSSF 中,颜色总是需要调色板颜色。因此,如果需要自定义颜色,则需要覆盖其他 HSSFPalette 颜色之一。
以下是适用于 XSSFHSSF 的完整示例。对于 HSSF,它将使用 RGB 222、111、222 覆盖 HSSFColor.HSSFColorPredefined.LIME
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();

 }

}

好的,它运行良好。我还有一个问题,我可以将其用于单元格前景色吗? - demir5334
@demir5334:请参考 https://stackoverflow.com/questions/53117806/adding-custom-colours-to-excel-sheet-using-apache-poi/53120147#53120147。 - Axel Richter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接