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

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

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); } } 

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

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

我正在使用VSTO,C#

以下代码将条件格式添加到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; 

尝试这个

 FormatCondition cond = ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, "=$B1"); cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); 

假设你想为单元格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 

请注意,需要将"="置于ColumnARange.Address[false,true] ,因为否则, Add方法使用Address作为文本string而不是单元格引用。

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

为了完整:我使用Range.Address属性上的可选对象,如Range.Address[isRowAbsolute,isColumnAbsolute]