Excel 和 .NET 的细粒度单元格着色

Fine Grained Cell Coloring with Excel and .NET

Microsoft 提供了 .NET API 以编程方式设置单元格颜色

Excel.Range rng2 = this.Application.get_Range("A1");
rng2.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

有没有办法在

中有两种不同的颜色

是的,您可以为字符的颜色这样做。你不能为背景。只能对整个单元格进行背景着色

这是一个片段(省略了 XlColors 枚举的定义)

        private static readonly Dictionary<string, XlColors> WordColoring = new Dictionary<string, XlColors>
                       {
                            {"linksaf", XlColors.Red},
                            {"schuin links", XlColors.Red},
                            {"links aanhouden", XlColors.Red},
                            {"rechtsaf", XlColors.Greenish},
                            {"schuin rechts", XlColors.Greenish},
                            {"rechts aanhouden", XlColors.Greenish},
                            {"rechtdoor", XlColors.Blue}
                       };

    public void TekstFormatter(Range cell)
    {
        string text = (cell.Value2 ?? "");

        foreach (KeyValuePair<string, XlColors> colorPair in WordColoring)
        {
            int pos = text.IndexOf(colorPair.Key, StringComparison.OrdinalIgnoreCase);
            if (pos != -1)
            {
                Characters chars = cell.Characters[pos + 1, colorPair.Key.Length];
                chars.Font.Color = colorPair.Value;
                chars.Font.Bold = true;
            }                
        }
    }