Important
1. 不同的颜色需要设置到不同的索引处,否则会被覆盖。
2. 索引的范围是有限的,需要在调色板中预设自定义色,在注释中有说明。
var hssfworkbook = new HSSFWorkbook();
ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
//fill background
ICellStyle style1 = hssfworkbook.CreateCellStyle();
#region 使用调色板生成基于 hex 的自定义颜色
var palette = hssfworkbook.GetCustomPalette();
// hex to argb
// ColorTranslator 静态类:
// .net framework 添加本地 dll 引用,然后再导入 using System.Drawing; 命名空间
// .net(core) 从 nuget 添加 System.Drawing.Common 包,然后再导入 using System.Drawing; 命名空间
var argb = ColorTranslator.FromHtml("#ff0303");
// 索引值在底层使用时会 index-8,相减后的差值必须满足 num >= 0 && num < 56
var customBackgroundColorIndexInPalette = (short)8;
palette.SetColorAtIndex(customBackgroundColorIndexInPalette, argb.R, argb.G, argb.B);
#endregion
// 设置单元格背景色必须用 FillForegroundColor + FillPattern 两个字段,用 FillBackgroundColor 字段无法设置背景色
// 设置前景色和填充模式,前景色取自调色板指定索引处的 RGB 颜色
style1.FillForegroundColor = customBackgroundColorIndexInPalette; //NPOI.HSSF.Util.HSSFColor.Blue.Index;
style1.FillPattern = FillPattern.SolidForeground;
// 创建位置为 0,0 的单元格,设置单元格内容和样式
var cell00 = sheet1.CreateRow(0).CreateCell(0);
cell00.SetCellValue("hi");
cell00.CellStyle = style1;
调色板自定义 RGB 色:
// 自定义统计颜色(3个档次对应3个颜色)在 Excel 工作簿自定义调色板中的颜色索引
private static readonly short _color1IndexInWorkbookCustomPalette = 8;
private static readonly short _color2IndexInWorkbookCustomPalette = 9;
private static readonly short _color3IndexInWorkbookCustomPalette = 10;
// 在 Excel 工作簿的自定义调色板中预设所有自定义颜色
private static void SetAllColorIndexOnWorkbookCustomPalette(HSSFWorkbook workbook)
{
SetColorIndexOnWorkbookCustomPalette(workbook, _color1IndexInWorkbookCustomPalette, ConfigHelper.Setting.Color1);
SetColorIndexOnWorkbookCustomPalette(workbook, _color2IndexInWorkbookCustomPalette, ConfigHelper.Setting.Color2);
SetColorIndexOnWorkbookCustomPalette(workbook, _color3IndexInWorkbookCustomPalette, ConfigHelper.Setting.Color3);
}
// 在 Excel 工作簿的自定义调色板中的指定索引处设置自定义的 hex 格式的颜色
private static void SetColorAtIndexOnWorkbookCustomPalette(HSSFWorkbook workbook,short rgbColorIndexInPalette, string hexColor)
{
if (rgbColorIndexInPalette < 8 || rgbColorIndexInPalette > 56) throw new IndexOutOfRangeException(nameof(rgbColorIndexInPalette));
var palette = workbook.GetCustomPalette();
var argb = ColorTranslator.FromHtml(hexColor);
palette.SetColorAtIndex(rgbColorIndexInPalette, argb.R, argb.G, argb.B);
}