使用 Apache POI 向 Excel 工作表添加自定义颜色

Nik*_*chu 1 java apache-poi

任何人都可以解释如何使用(rgb 值或十六进制值)将自定义颜色添加到 Excel 表(在前景或背景中)使用 Apche poi 中的 Cellstyle 到 Excel 表(XSSF 工作簿)?

Axe*_*ter 5

设置自定义颜色取决于Excel文件类型(Office Open XML 格式*.xlsx与 BIFF 格式*.xls)。apache poi由于弃用,使用不同版本的可能会有所不同。

使用 Office Open XML 格式,*.xlsx我们可以使用XSSFColor 的构造函数简单地设置新颜色。在apache poi 4.0.0 XSSFColor(byte[] rgb, IndexedColorMap colorMap)可以使用。IndexedColorMapnull如果没有其他颜色的地图应使用而不是默认的一个。

使用 BIFF 格式*.xls只能使用索引颜色。但是暂时覆盖某些索引颜色是可能的。

以下代码显示了用于设置单元格填充颜色的两者。使用的自定义颜色是 RGB(112,134,156)。使用HSSF(BIFF 格式*.xls)索引颜色HSSFColor.HSSFColorPredefined.LIME将被临时覆盖。

请注意,以下内容经过测试并使用apache poi 4.0.0. 不保证使用其他版本。

import java.io.FileOutputStream;

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

public class CreateExcelCustomColor {

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

  Workbook workbook = new XSSFWorkbook();
  //Workbook workbook = new HSSFWorkbook();

  CellStyle cellcolorstyle = workbook.createCellStyle();
  cellcolorstyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  byte[] rgb = new byte[]{(byte)112, (byte)134, (byte)156};
  if (cellcolorstyle instanceof XSSFCellStyle) {
   XSSFCellStyle xssfcellcolorstyle = (XSSFCellStyle)cellcolorstyle;
   xssfcellcolorstyle.setFillForegroundColor(new XSSFColor(rgb, null));
  } else if (cellcolorstyle instanceof HSSFCellStyle) {
   cellcolorstyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIME.getIndex());
   HSSFWorkbook hssfworkbook = (HSSFWorkbook)workbook;
   HSSFPalette palette = hssfworkbook.getCustomPalette();
   palette.setColorAtIndex(HSSFColor.HSSFColorPredefined.LIME.getIndex(), rgb[0], rgb[1], rgb[2]);
  }

  Sheet sheet = workbook.createSheet();
  Cell cell = sheet.createRow(0).createCell(0);
  cell.setCellStyle(cellcolorstyle);

  FileOutputStream out = null; 
  if (workbook instanceof XSSFWorkbook) {
   out = new FileOutputStream("CreateExcelCustomColor.xlsx");
  } else if (workbook instanceof HSSFWorkbook) {
   out = new FileOutputStream("CreateExcelCustomColor.xls");
  }
  workbook.write(out);
  out.close();
  workbook.close();

 }

}
Run Code Online (Sandbox Code Playgroud)