C# 用C语言实现Excel中的条件格式#
如果值与另一列中的值不同,我需要对单元格的文本应用颜色。最好的方法是什么?我能想到的方法是相当昂贵的C# 用C语言实现Excel中的条件格式#,c#,excel,vsto,C#,Excel,Vsto,如果值与另一列中的值不同,我需要对单元格的文本应用颜色。最好的方法是什么?我能想到的方法是相当昂贵的 for (int i = 0; i < ColumnARange.Cells.Count; i++) { if (ColumnARange.Cells[i, 1] != ColumnBRange.Cells[i, 1]) {
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);
}
}
我使用的是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
,即
B1A1
导致B1
着色,B2A2
导致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
请注意,必须将“=”
预加到列范围。地址[false,true]
,否则Add
方法将Address
用作文本字符串,而不是单元格引用
如果查看Excel工作表中应用于B1:B10
单元格的条件格式规则,它将为该范围内的每个单元格声明单元格值B1
,这在我看来有点混乱,但格式应用正确
为了完整性:我在
Range.Address
属性上使用可选对象,比如soRange.Address[isRowAbsolute,isColumnAbsolute]
是。需要通过与其他列的值进行比较,将颜色应用于单元格文本。但是,如果我像代码中提到的那样进行遍历,考虑到具有更多行和列的大型数据,这将非常昂贵。但是如何处理动态范围?@buffer_overflow检查get_range方法的声明,可以分别使用targetSheet.Cells[1,2]和targetSheet.Cells[3,4]提供单元格1和单元格2。我希望你知道,如果只有一列是重复的呢?检查所有D1
,例如。。。如果存在两个重复项,请将其高亮显示。您需要更改列=COUNTIF($A$1:$A$10,A1)=1中重复项的条件,其中A1到A10是您的值范围。
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