首页 > 解决方案 > NPOI:将单元格颜色设置为自定义颜色

问题描述

如何使用 C# NPOI 将单元格颜色设置为自定义颜色?我知道如何使用颜色索引更改带有 NPOI 的单元格的颜色:

XSSFCellStyle cellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
cellStyle.FillBackgroundColor = IndexedColors.LightCornflowerBlue.Index;
cellStyle.FillForegroundColor = IndexedColors.LightCornflowerBlue.Index;
cellStyle.FillPattern = FillPattern.SolidForeground;
ICell cell = CurrentRow.CreateCell(CellIndex);
cell.CellStyle = cellStyle;

但是,我想使用自定义颜色。IndexedColors 是有限的,没有那么有用。我已经四处寻找答案很长时间了。


几年前我发现了这篇文章,但它似乎不再相关。SetFillForegroundColor 现在是短的,不再是 XSSFColor。

byte[] rgb = new byte[3] { 192, 0, 0 };
XSSFCellStyle HeaderCellStyle1 = (XSSFCellStyle)xssfworkbook.CreateCellStyle();
HeaderCellStyle1.SetFillForegroundColor(new XSSFColor(rgb));

标签: c#apache-poinpoi

解决方案


我应该一直使用 FillBackgroundXSSFColor 而不是 FillBackgroundColor

XSSFCellStyle cellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
byte[] rgb = new byte[3] { 255, 221, 221 };
XSSFColor color = new XSSFColor(rgb);
cellStyle.FillBackgroundXSSFColor = color;
ICell cell = CurrentRow.CreateCell(CellIndex);
cell.CellStyle = cellStyle;

推荐阅读