当前位置: 代码迷 >> 综合 >> C#使用NPOI设置Excel单元格背景颜色(xls,xlsx)
  详细解决方案

C#使用NPOI设置Excel单元格背景颜色(xls,xlsx)

热度:31   发布时间:2023-09-27 01:49:21.0

        每次用到这个都要去百度,这里记录一下,xls和xlsx两种格式设置背景颜色的区别,这里省略了前面读取模板或者创建excel的过程:

xls:

ICellStyle style = workbook.CreateCellStyle();//使用NPOI已经有的颜色创建
style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
style.FillPattern = FillPattern.SolidForeground;//没有的颜色,使用RGB值进行创建
//这里要自定义一个颜色板覆盖掉原来的index,这里覆盖48号位置上的
HSSFPalette palette = ((HSSFWorkbook)workbook).GetCustomPalette();
palette.SetColorAtIndex(48, 0, 112, 192);
style.FillForegroundColor = palette.FindColor(0, 112, 192).Indexed;

xlsx:

ICellStyle style = workbook.CreateCellStyle();//使用NPOI已经有的颜色创建(这里跟xls一样,不知道为什么可以通用)
style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
style.FillPattern = FillPattern.SolidForeground;//使用没有的颜色,这里和xls不一样,不需要覆盖掉原来的色板
style.FillForegroundColor = 0;
style.FillPattern = FillPattern.SolidForeground;
((XSSFColor)style.FillForegroundColorColor).SetRgb(new byte[] { 0, 176, 240 });

  相关解决方案