簡體   English   中英

使用 C# 在 Excel 中進行條件格式設置

[英]Conditional Formatting in Excel with C#

如果值與另一列中的值不同,我需要將顏色應用於單元格的文本。 什么是最好的方法? 我能想到的方法是相當昂貴的。

 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;

假設您要為單元格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方法ColumnARange.Address[false,true] Address用作文字字符串而不是單元格引用。

如果您查看應用於 Excel 工作表中B1:B10單元格的條件格式規則,它將為該范圍內的每個單元格聲明Cell Value <> B1 ,這有點令人困惑 IMO,但格式仍然正確應用。

為了完整性:我在Range.Address屬性上使用可選對象,如Range.Address[isRowAbsolute,isColumnAbsolute]

試試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM