NPOI excel 单元格背景色

需求描述:如下图所示,不合格的单元格,背景色要为灰色。

解决方法:不建议使用新样式的方式来实现,因为会破坏原单元格的样式(例如边框、字体),所以只需要修改原样式即可,但有时候原样式是共享的,也就是很多单元格用同一个样式,所以解决思路是复制一个新样式给该单元格即可。

 

核心代码:

        /// <summary>
        /// 给单元格设置背景颜色
        /// </summary>
        /// <param name="cell">单元格</param>
        private void SetTextBackgroundColor(IWorkbook wb, ICell cell)
        {
            if (cell.StringCellValue == "不合格")
            {
                ICellStyle style = wb.CreateCellStyle();
                style.CloneStyleFrom(cell.CellStyle);
                style.FillForegroundColor = HSSFColor.Grey25Percent.Index;
                style.FillPattern = FillPattern.SolidForeground;
                cell.CellStyle = style;
            }
        }

RGB方式(最好使用NPOI定义的枚举,使用自定义RGB,生成的excel没问题,但是excel转其他文件会有样式丢失情况):

        /// <summary>
        /// 给单元格设置背景颜色
        /// </summary>
        /// <param name="cell">单元格</param>
        private void SetTextBackgroundColor(IWorkbook wb, ICell cell)
        {
            if (cell.StringCellValue == "不合格")
            {
                ICellStyle style = wb.CreateCellStyle();
                style.CloneStyleFrom(cell.CellStyle);
                //style.FillForegroundColor = HSSFColor.Grey25Percent.Index;
                style.FillPattern = FillPattern.SolidForeground;
                byte r = 247;
                byte g = 253;
                byte b = 157;
                
                if (wb is XSSFWorkbook)
                {
                    style.FillForegroundColor = 0;
                    ((XSSFColor)style.FillForegroundColorColor).SetRgb(new byte[] { r, g, b });
                }
                else
                {
                    style.FillForegroundColor = (((HSSFWorkbook)wb).GetCustomPalette().FindSimilarColor(r, g, b)).Indexed;
                }
                cell.CellStyle = style;
            }
        }

 

posted @ 2023-12-11 10:47  0Behavior  阅读(458)  评论(2编辑  收藏  举报