You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:06:12