使用C#在Excel中进行条件格式化

Can*_*non 6 c# excel vsto

如果值与另一列中的值不同,我需要将颜色应用于单元格的文本.最好的方法是什么?我能想到的方式非常昂贵.

 for (int i = 0; i < ColumnARange.Cells.Count; i++)
                    {
                        if (ColumnARange.Cells[i, 1] != ColumnBRange.Cells[i, 1])
                        {
                            Range currCell = ColumnBRange.Cells[i, 1];
                            currCell.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
                        }
                    }
Run Code Online (Sandbox Code Playgroud)

尝试条件格式如下,但徒劳无功.

FormatCondition cond = ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, ColumnARange);
                cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
Run Code Online (Sandbox Code Playgroud)

我正在使用VSTO,C#

Aka*_*aur 7

以下代码将条件格式添加到D1到E10的单元格区域

它分别比较值D1 = E1或D2 = E2.您可以在FormatCondition对象上设置字体颜色或颜色填充.

FormatCondition format =(FormatCondition)( targetSheet.get_Range("D1:E10",
                Type.Missing).FormatConditions.Add(XlFormatConditionType.xlExpression, XlFormatConditionOperator.xlEqual,
                "=$D1=$E1", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing));

            format.Font.Bold = true;
            format.Font.Color = 0x000000FF;
Run Code Online (Sandbox Code Playgroud)


joi*_*lds 6

假设您想为单元格着色,B1:B10如果它们的值不等于 的值A1:A10,即

B1<>A1导致B1被着色,B2<>A2导致B2被着色等。

然后您可以执行以下操作

Range columnBRange = (Range)oSheet.Range[oSheet.Cells[1,2], oSheet.Cells[10,2]];

Range columnARange = (Range)oSheet.Range[oSheet.Cells[1,1], oSheet.Cells[1,1]];

FormatCondition cond = (FormatCondition) ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, "="+ColumnARange.Address[false,true]);
cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); //Red letters
cond.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightYellow); //Light yellow cell background
Run Code Online (Sandbox Code Playgroud)

请注意,需要预先添加"="to ColumnARange.Address[false,true],否则该Add方法将使用 theAddress作为文字字符串而不是单元格引用。

如果您查看应用于B1:B10Excel 工作表中单元格的条件格式规则,它将Cell Value <> B1为该范围内的每个单元格声明,这有点令人困惑 IMO,但格式仍然正确应用。

为了完整性:我Range.Address像这样在属性 上使用可选对象Range.Address[isRowAbsolute,isColumnAbsolute]