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 @   0Behavior  阅读(565)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示