如何在C# EPPlus WPF环境下判断Excel工作表单元格的文本颜色
EPPlus 实现单元格首字符颜色非白校验方案
你提供的VBA代码逻辑是校验目标单元格第一个字符的字体颜色不等于白色,对应EPPlus的实现代码如下:
using OfficeOpenXml; using System.Drawing; // 前置操作:已获取ExcelWorksheet实例excelSheet,row、column为目标单元格的1-based行号、列号 var targetCell = excelSheet.Cells[row, column]; Color firstCharColor; if (targetCell.IsRichText) { // 富文本单元格取第一个文本片段的颜色 firstCharColor = targetCell.RichText[0].Color; } else { // 普通文本单元格取全局字体颜色 firstCharColor = targetCell.Style.Font.Color.Color; } // 等效于VBA的 excelSheet.Cells(row,Column).Characters(1, 1).Font.Color <> vbWhite bool isNotWhite = firstCharColor != Color.White;
补充说明
- 若需要校验单元格内所有字符颜色都不是白色,遍历富文本所有片段判断即可:
bool allCharNotWhite = true; if (targetCell.IsRichText) { foreach (var textPart in targetCell.RichText) { if (textPart.Color == Color.White) { allCharNotWhite = false; break; } } } else { allCharNotWhite = targetCell.Style.Font.Color.Color != Color.White; }
- EPPlus的行号、列号从1开始计数,和VBA逻辑一致无需额外转换
- 若字体颜色通过Excel主题色设置,需通过
targetCell.Style.Font.Color.ThemeColor获取主题色索引后再做匹配 - EPPlus 5及以上版本使用前需提前设置许可上下文,非商业使用场景添加代码:
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
内容的提问来源于stack exchange,提问作者User_AA
相关产品推荐
相关产品推荐

