How to Apply Conditional Formatting to Cells

How to Apply Conditional Formatting in Excel with C#

Apply conditional formatting in C# using IronXL's simple API to create rules with comparison operators and styling options, then apply them to specific cell ranges in your Excel spreadsheets.

Conditional formatting is a feature in spreadsheet and data processing software that allows you to apply specific formatting styles or rules to cells or data based on certain conditions or criteria. It enables you to visually highlight or emphasize data that meets particular conditions or criteria, making it easier to analyze and understand data in a spreadsheet or table. Whether you're working with existing Excel files or creating new spreadsheets from scratch, IronXL provides comprehensive support for implementing conditional formatting rules.

Add, retrieve, and remove conditional formatting with IronXL. When adding conditional formatting with styling, you can make font and size adjustments, set borders and alignment, and define background patterns and colors. These formatting options work seamlessly with other Excel features like formulas and cell data formats.

Quickstart: Add a 'Less Than' Formatting Rule Effortlessly

Get started fast with IronXL: create a conditional formatting rule using just one line and apply it to a range of cells. Define your condition and style, and IronXL handles the rest.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronXL with NuGet Package Manager

    PM > Install-Package IronXL.Excel

  2. Copy and run this code snippet.

    var rule = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(ComparisonOperator.LessThan, "8"); workSheet.ConditionalFormatting.AddConditionalFormatting("A1:A10", rule);
  3. Deploy to test on your live environment

    Start using IronXL in your project today with a free trial
    arrow pointer


Get started with IronXL

Start using IronXL in your project today with a free trial.

First Step:
green arrow pointer


How Do I Add Conditional Formatting Rules?

Conditional formatting consists of rules and styles that are applied when a cell meets the specified rule criteria. The styles can include font and size adjustments, borders and alignment settings, as well as background patterns and colors. These formatting capabilities integrate perfectly with IronXL's ability to select ranges and work with specific cell collections.

To define a rule, use the CreateConditionalFormattingRule method provided by IronXL. Assign the object returned by this method to a variable, and use it to apply the desired styling. Finally, use the AddConditionalFormatting method, providing both the created rule and the cell range to which it should be applied. This approach is similar to how you would manage worksheets or work with other Excel features programmatically.

What comparison operators are available?

IronXL supports a comprehensive set of comparison operators that allow you to create sophisticated conditional formatting rules. These operators work seamlessly with numeric values, dates, and even text comparisons when appropriate. The available rules are:

  • NoComparison: Default value, used when applying formatting without comparison
  • Between: Highlights values within a specific range
  • NotBetween: Highlights values outside a specified range
  • Equal: Matches exact values
  • NotEqual: Excludes specific values
  • GreaterThan: Highlights values above a threshold
  • LessThan: Highlights values below a threshold
  • GreaterThanOrEqual: Includes the threshold value
  • LessThanOrEqual: Includes the threshold value

These operators can be combined with various data types and work particularly well when analyzing data that you've imported from CSV files or other sources.

How do I style the conditional formatting?

When creating conditional formatting rules, IronXL provides extensive styling options. You can customize the appearance of cells that meet your conditions by modifying various visual properties. The following example demonstrates how to create a rule and apply background color styling:

:path=/static-assets/excel/content-code-examples/how-to/conditional-formatting-add.cs
using IronXL;
using IronXL.Formatting.Enums;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Create conditional formatting rule
var rule = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(ComparisonOperator.LessThan, "8");

// Set style options
rule.PatternFormatting.BackgroundColor = "#54BDD9";

// Add conditional formatting rule
workSheet.ConditionalFormatting.AddConditionalFormatting("A1:A10", rule);

workBook.SaveAs("addConditionalFormatting.xlsx");
Imports IronXL
Imports IronXL.Formatting.Enums

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Create conditional formatting rule
Private rule = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(ComparisonOperator.LessThan, "8")

' Set style options
rule.PatternFormatting.BackgroundColor = "#54BDD9"

' Add conditional formatting rule
workSheet.ConditionalFormatting.AddConditionalFormatting("A1:A10", rule)

workBook.SaveAs("addConditionalFormatting.xlsx")
$vbLabelText   $csharpLabel

The PatternFormatting property provides access to various styling options beyond just background color. You can also modify pattern styles, foreground colors, and pattern fills to create more complex visual indicators. This flexibility allows you to create formatting that matches your organization's branding or makes specific data patterns immediately recognizable.

What does the formatting look like when applied?

Spreadsheet with columns A and B containing numbers 1-10 before conditional formatting is applied
Spreadsheet with blue conditional formatting applied to cells A1-A7, showing formatted vs unformatted columns

How Do I Retrieve Existing Conditional Formatting?

Working with existing conditional formatting is essential when you need to modify spreadsheets that already contain formatting rules or when you want to analyze the formatting logic applied to specific ranges. IronXL makes it straightforward to access and modify these existing rules.

To retrieve a conditional formatting rule, use the GetConditionalFormattingAt method. The rule object returned may contain multiple rules; use the GetRule method to access a specific one. Most properties of a retrieved rule cannot be modified, but you can adjust the BackgroundColor via the PatternFormatting property. This limitation ensures that the core logic of the rule remains intact while still allowing for visual customization.

What properties can I modify on existing rules?

While working with retrieved conditional formatting rules, understand which properties can be modified. The primary modifiable property is the background color, which allows you to update the visual appearance without changing the underlying condition logic. Here's an example that demonstrates retrieving and modifying an existing rule:

:path=/static-assets/excel/content-code-examples/how-to/conditional-formatting-retrieve.cs
using IronXL;

WorkBook workBook = WorkBook.Load("addConditionalFormatting.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Create conditional formatting rule
var ruleCollection = workSheet.ConditionalFormatting.GetConditionalFormattingAt(0);
var rule = ruleCollection.GetRule(0);

// Edit styling
rule.PatternFormatting.BackgroundColor = "#B6CFB6";

workBook.SaveAs("editedConditionalFormatting.xlsx");
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("addConditionalFormatting.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Create conditional formatting rule
Private ruleCollection = workSheet.ConditionalFormatting.GetConditionalFormattingAt(0)
Private rule = ruleCollection.GetRule(0)

' Edit styling
rule.PatternFormatting.BackgroundColor = "#B6CFB6"

workBook.SaveAs("editedConditionalFormatting.xlsx")
$vbLabelText   $csharpLabel

This approach is particularly useful when you need to update the visual theme of a spreadsheet while preserving the business logic embedded in the conditional formatting rules.

How do I access multiple rules in a collection?

When working with complex spreadsheets, you may encounter multiple conditional formatting rules applied to the same range or overlapping ranges. The GetConditionalFormattingAt method returns a collection that can contain multiple rules. You can iterate through these rules using standard collection methods or access specific rules by their index using GetRule(index). This functionality is especially valuable when working with data from various sources that may have different formatting requirements.

Excel spreadsheet showing rows 1-7 in column A highlighted with blue conditional formatting, rows 8-10 unformatted
Excel spreadsheet with green conditional formatting applied to cells A1-A10 containing numbers 1-10

How Do I Remove Conditional Formatting?

There are scenarios where you need to remove conditional formatting rules entirely. This might be necessary when preparing data for export, simplifying spreadsheet maintenance, or when the formatting rules are no longer relevant to your current data analysis needs.

To remove a conditional formatting rule, use the RemoveConditionalFormatting method. Pass the index of the targeted rule to this method. This operation is permanent for the current workbook instance, though you can always reload the original file if needed.

When should I remove conditional formatting rules?

Consider removing conditional formatting rules in these situations:

  • Data Export: When exporting to different formats without formatting support
  • Performance Optimization: Complex rules can impact performance with large datasets
  • Rule Conflicts: Multiple overlapping rules create confusion or unexpected results
  • Simplified Analysis: Preparing data for automated processing where formatting is unnecessary
  • Template Creation: Creating clean templates for others to use
:path=/static-assets/excel/content-code-examples/how-to/conditional-formatting-remove.cs
using IronXL;

WorkBook workBook = WorkBook.Load("addConditionalFormatting.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Remove conditional formatting rule
workSheet.ConditionalFormatting.RemoveConditionalFormatting(0);

workBook.SaveAs("removedConditionalFormatting.xlsx");
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("addConditionalFormatting.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Remove conditional formatting rule
workSheet.ConditionalFormatting.RemoveConditionalFormatting(0)

workBook.SaveAs("removedConditionalFormatting.xlsx")
$vbLabelText   $csharpLabel

What happens to cell styles after removal?

When you remove conditional formatting rules, only the conditional formatting is removed—the underlying cell data and any direct formatting remain unchanged. The cells revert to their base formatting, which includes any styles that were applied directly to the cells rather than through conditional rules. If a cell had a specific font, border, or fill color applied directly (not through conditional formatting), those styles remain after the conditional formatting is removed.

This behavior ensures that your data integrity is maintained while giving you complete control over the visual presentation of your spreadsheets. For more advanced formatting needs, explore IronXL's comprehensive API reference to understand all available formatting options.

Frequently Asked Questions

How do I add conditional formatting to Excel cells in C#?

IronXL makes it simple to add conditional formatting in C#. First, create a conditional formatting rule using the CreateConditionalFormattingRule method with your desired comparison operator and value. Then apply it to a cell range using the AddConditionalFormatting method. For example: var rule = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(ComparisonOperator.LessThan, "8"); workSheet.ConditionalFormatting.AddConditionalFormatting("A1:A10", rule);

What comparison operators are available for conditional formatting rules?

IronXL supports various comparison operators for conditional formatting rules including LessThan, GreaterThan, Equal, NotEqual, and more. You specify the operator when creating a rule with the CreateConditionalFormattingRule method, allowing you to highlight cells based on different criteria like values less than 8, greater than 100, or equal to specific text.

Can I apply multiple styles with conditional formatting?

Yes, IronXL allows you to apply comprehensive styling with conditional formatting rules. You can make font and size adjustments, set borders and alignment, and define background patterns and colors. These formatting options work seamlessly with other Excel features like formulas and cell data formats, giving you complete control over how cells appear when conditions are met.

How do I retrieve existing conditional formatting rules from an Excel file?

IronXL provides the GetConditionalFormattingAt method to retrieve existing conditional formatting rules from Excel files. This allows you to examine, modify, or remove rules that were previously applied to specific cell ranges, making it easy to manage and update conditional formatting in existing spreadsheets.

Does conditional formatting work with both new and existing Excel files?

Yes, IronXL provides comprehensive support for implementing conditional formatting rules whether you're working with existing Excel files or creating new spreadsheets from scratch. You can load an existing spreadsheet and add conditional formatting, or create a new workbook and apply formatting rules as you build your data.

Can I remove conditional formatting rules programmatically?

IronXL allows you to add, retrieve, and remove conditional formatting rules programmatically. This gives you full control over managing conditional formatting in your Excel files, enabling you to dynamically update or clear formatting based on your application's requirements.

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.
Ready to Get Started?
Nuget Downloads 1,765,830 | Version: 2025.12 just released