使用Apche POI将自定义颜色添加到Excel工作表

时间:2018-11-02 11:32:03

标签: java apache-poi

谁能解释如何使用Apche poi中的Cellstyle将Excel表格(前景值或背景值)(rgb值或十六进制值)添加到Excelsheet(XSSF工作簿)吗?

1 个答案:

答案 0 :(得分:2)

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

使用Office Open XML格式*.xlsx,我们可以简单地使用XSSFColor的构造函数设置新颜色。在apache poi 4.0.0中可以使用XSSFColor(byte[] rgb, IndexedColorMap colorMap)。如果不使用其他颜色映射代替默认颜色映射,则IndexedColorMap可以是null

使用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();

 }

}
相关问题