Easiest Ways to Highlight Data in Excel Using C# | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (217)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (917)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (148)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (629)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (593)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Easiest Ways to Highlight Data in Excel Using C#

Easiest Ways to Highlight Data in Excel Using C#

Conditional formatting helps identify an Excel spreadsheet’s data by highlighting cells based on certain criteria provided by the user. This feature overrides any default cell styles in the worksheet when the cell value matches the criteria. This blog will discuss how to implement conditional formatting in Excel spreadsheets using Syncfusion’s .NET Excel Library in C#.

The following types of conditional formatting are available in Excel Library:

Enjoy a smooth experience with Syncfusion’s Excel Library! Get started with a few lines of code and without Microsoft or interop dependencies.

Cell rules

In this type, conditional formatting is applied directly to specific cells based on the cell value. The specified formatting will be applied if the cell value matches the condition. For example, you can use this type of formatting to highlight expenses in an expense report. When an expense falls below $10,000, you can highlight it green, or if it is above that threshold, it can be highlighted red. Doing so provides visual distinctions between low and high expenses.

The following code example shows how to highlight cell values with conditional formatting using specific cell rules.

using System.IO;
using Syncfusion.XlsIO;

namespace Create_Conditional_Format
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                IApplication application = excelEngine.Excel;
                application.DefaultVersion = ExcelVersion.Xlsx;
                IWorkbook workbook = application.Workbooks.Create(1);
                IWorksheet worksheet = workbook.Worksheets[0];

                //Applying conditional formatting to "A1".
                IConditionalFormats condition = worksheet.Range["A1"].ConditionalFormats;
                IConditionalFormat condition1 = condition.AddCondition();

                //Represents conditional format rule that the value in the target range should be between 10 and 20.
                condition1.FormatType = ExcelCFType.CellValue;
                condition1.Operator = ExcelComparisonOperator.Between;
                condition1.FirstFormula = "10";
                condition1.SecondFormula = "20";
                worksheet.Range["A1"].Text = "Enter a number between 10 and 20";

                //Setting back color and font style to be applied for the target range.
                condition1.BackColor = ExcelKnownColors.Light_orange;
                condition1.IsBold = true;
                condition1.IsItalic = true;

                //Applying conditional formatting to "A3".
                condition = worksheet.Range["A3"].ConditionalFormats;
                IConditionalFormat condition2 = condition.AddCondition();

                //Represents conditional format rule that the cell value should be 1000.
                condition2.FormatType = ExcelCFType.CellValue;
                condition2.Operator = ExcelComparisonOperator.Equal;
                condition2.FirstFormula = "1000";
                worksheet.Range["A3"].Text = "Enter the Number as 1000";

                //Setting fill pattern and back color to the target range.
                condition2.FillPattern = ExcelPattern.LightUpwardDiagonal;
                condition2.BackColor = ExcelKnownColors.Yellow;

                //Applying conditional formatting to "A5".
                condition = worksheet.Range["A5"].ConditionalFormats;
                IConditionalFormat condition3 = condition.AddCondition();

                //Setting conditional format rule that the cell value for the target range should be less than or equal to 1000.
                condition3.FormatType = ExcelCFType.CellValue;
                condition3.Operator = ExcelComparisonOperator.LessOrEqual;
                condition3.FirstFormula = "1000";
                worksheet.Range["A5"].Text = "Enter a Number which is less than or equal to 1000";

                //Setting back color to target range.
                condition3.BackColor = ExcelKnownColors.Light_green;

                #region Save
                //Saving the workbook.
                FileStream outputStream = new FileStream("ConditionalFormat.xlsx", FileMode.Create, FileAccess.Write);
                workbook.SaveAs(outputStream);
                #endregion

                //Dispose streams.
                outputStream.Dispose();
            }
        }
    }
}

After applying the cell values in the Excel spreadsheet generated from the above code example, the output will look like the following screenshot.

Cell Rules Conditional Formatting Applied to an Excel Spreadsheet
Cell Rules Conditional Formatting Applied to an Excel Spreadsheet

Note: For more details, refer to the cell rules in .NET Excel Library documentation.

Top and bottom values

In this type, Excel Library automatically detects the values in a specific range and highlights the top and bottom n number of cells based on the conditional formatting styles.

You can highlight the top 10 expenses in an expense report using this conditional formatting type. You can also use this formatting to highlight unique and duplicate numbers, as well as numbers above and below an average.

using System.IO;
using Syncfusion.XlsIO;

namespace Top_to_Bottom_Rank
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                IApplication application = excelEngine.Excel;
                application.DefaultVersion = ExcelVersion.Xlsx;
                FileStream inputStream = new FileStream("../../../Data/InputTemplate.xlsx", FileMode.Open, FileAccess.Read);
                IWorkbook workbook = application.Workbooks.Open(inputStream);
                IWorksheet worksheet = workbook.Worksheets[0];

                //Applying conditional formatting to "N6:N35".
                IConditionalFormats formats = worksheet.Range["N6:N35"].ConditionalFormats;
                IConditionalFormat format = formats.AddCondition();

                //Applying top or bottom rule in the conditional formatting.
                format.FormatType = ExcelCFType.TopBottom;
                ITopBottom topBottom = format.TopBottom;

                //Set type as Top for TopBottom rule.
                topBottom.Type = ExcelCFTopBottomType.Top;

                //Set rank value for the TopBottom rule.
                topBottom.Rank = 10;

                //Set color for Conditional Formattting.
                format.BackColorRGB = Syncfusion.Drawing.Color.FromArgb(51, 153, 102);

                #region Save
                //Saving the workbook.
                FileStream outputStream = new FileStream("TopToBottomRank.xlsx", FileMode.Create, FileAccess.Write);
                workbook.SaveAs(outputStream);
                #endregion

                //Dispose streams.
                outputStream.Dispose();
                inputStream.Dispose();
            }
        }
    }
}

The output of the above code example will look like the following screenshot.

Top and Bottom Conditional Formatting in Excel Spreadsheet
Top and Bottom Conditional Formatting in Excel Spreadsheet

Note: For more details, refer to the top and bottom values formatting in .NET Excel Library documentation.

Color scales

While using color scale formatting, the cell color intensity will increase from bottom to top values in a cell range between specified colors. This helps identify one cell value’s place within a larger set of data. For example, we can highlight a yearly sales report divided by month with a color scale to show which months had higher or lower sales and compare other months’ sales through cell color intensity.

Refer to the following code example.

//Create a color scale for the data in the specified range.
IConditionalFormats conditionalFormats = worksheet.Range["D7:D46"].ConditionalFormats;
IConditionalFormat conditionalFormat = conditionalFormats.AddCondition();
conditionalFormat.FormatType = ExcelCFType.ColorScale;
IColorScale colorScale = conditionalFormat.ColorScale;

//Set a three-color scale and its constraints.
colorScale.SetConditionCount(3);
colorScale.Criteria[0].FormatColorRGB = Color.FromArgb(230, 197, 218);
colorScale.Criteria[0].Type = ConditionValueType.LowestValue;
colorScale.Criteria[0].Value = "0";

colorScale.Criteria[1].FormatColorRGB = Color.FromArgb(244, 210, 178);
colorScale.Criteria[1].Type = ConditionValueType.Percentile;
colorScale.Criteria[1].Value = "50";

colorScale.Criteria[2].FormatColorRGB = Color.FromArgb(245, 247, 171);
colorScale.Criteria[2].Type = ConditionValueType.HighestValue;
colorScale.Criteria[2].Value = "0";

Note: For more details, refer to the color scales in .NET Excel Library documentation.

Data bars

In this type, a color band is used inside a cell to show the top-to-bottom values in a specified cell range. Similar to a color scale, data bars also highlight the data but with a single color, whereas the color scale uses two or three colors. You can say data bars are a minimal version of bar charts in which bars are used inside a cell instead of on a separate chart in the Excel worksheet. An example of when to use data bars would be to highlight and present the value of a stock for over a period of time. The growth or decline of the stock values is easily understood by the different sizes of the data bars.

Refer to the following code example.

//Create data bars for the data in a specified range.
IConditionalFormats conditionalFormats = worksheet.Range["C7:C46"].ConditionalFormats;
IConditionalFormat conditionalFormat = conditionalFormats.AddCondition();
conditionalFormat.FormatType = ExcelCFType.DataBar;
IDataBar dataBar = conditionalFormat.DataBar;

//Set the constraints.
dataBar.MinPoint.Type = ConditionValueType.LowestValue;
dataBar.MaxPoint.Type = ConditionValueType.HighestValue;

//Set color for DataBar.
dataBar.BarColor = Color.FromArgb(156, 208, 243);

//Hide the data bar values.
dataBar.ShowValue = false;
dataBar.BarColor = Color.Aqua;

Note: For more details, refer to data bars in .NET Excel Library documentation.

Icon sets

Icon sets help group large amounts of data with icons, each with a specific threshold value. Similar to cell-rule formatting, when a specified condition matches, an icon is applied to the cell instead of any other formatting. For example, we can highlight an employee rating with five stars when the employee’s performance is extraordinary or noted with two stars when the performance is poor. In such a report, highlighting data with icons will be more suitable than using cell colors.

Refer to the following code example.

//Create icon sets for the data in a specified range.
IConditionalFormats conditionalFormats = worksheet.Range["E7:E46"].ConditionalFormats;
IConditionalFormat conditionalFormat = conditionalFormats.AddCondition();
conditionalFormat.FormatType = ExcelCFType.IconSet;
IIconSet iconSet = conditionalFormat.IconSet;

//Apply three symbol icons and hide the data in the specified range.
iconSet.IconSet = ExcelIconSetType.ThreeSymbols;
iconSet.IconCriteria[1].Type = ConditionValueType.Percent;
iconSet.IconCriteria[1].Value = "50";
iconSet.IconCriteria[2].Type = ConditionValueType.Percent;
iconSet.IconCriteria[2].Value = "50";
iconSet.ShowIconOnly = true;

The following code example shows how to use color scales, data bars, and icon sets to highlight data.

using System.IO;
using Syncfusion.XlsIO;
using Syncfusion.Drawing;

namespace Advanced_Conditional_Formats
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                IApplication application = excelEngine.Excel;
                application.DefaultVersion = ExcelVersion.Xlsx;
                FileStream inputStream = new FileStream("../../../Data/InputTemplate.xlsx", FileMode.Open, FileAccess.Read);
                IWorkbook workbook = application.Workbooks.Open(inputStream, ExcelOpenType.Automatic);
                IWorksheet worksheet = workbook.Worksheets[0];

                //Create data bars for the data in the specified range.
                IConditionalFormats conditionalFormats = worksheet.Range["C7:C46"].ConditionalFormats;
                IConditionalFormat conditionalFormat = conditionalFormats.AddCondition();
                conditionalFormat.FormatType = ExcelCFType.DataBar;
                IDataBar dataBar = conditionalFormat.DataBar;

                //Set the constraints.
                dataBar.MinPoint.Type = ConditionValueType.LowestValue;
                dataBar.MaxPoint.Type = ConditionValueType.HighestValue;

                //Set color for bar.
                dataBar.BarColor = Color.FromArgb(156, 208, 243);

                //Hide the values in the data bar.
                dataBar.ShowValue = false;
                dataBar.BarColor = Color.Aqua;

                //Create color scales for the data in a specified range.
                conditionalFormats = worksheet.Range["D7:D46"].ConditionalFormats;
                conditionalFormat = conditionalFormats.AddCondition();
                conditionalFormat.FormatType = ExcelCFType.ColorScale;
                IColorScale colorScale = conditionalFormat.ColorScale;

                //Sets three-color scale.
                colorScale.SetConditionCount(3);
                colorScale.Criteria[0].FormatColorRGB = Color.FromArgb(230, 197, 218);
                colorScale.Criteria[0].Type = ConditionValueType.LowestValue;
                colorScale.Criteria[0].Value = "0";

                colorScale.Criteria[1].FormatColorRGB = Color.FromArgb(244, 210, 178);
                colorScale.Criteria[1].Type = ConditionValueType.Percentile;
                colorScale.Criteria[1].Value = "50";

                colorScale.Criteria[2].FormatColorRGB = Color.FromArgb(245, 247, 171);
                colorScale.Criteria[2].Type = ConditionValueType.HighestValue;
                colorScale.Criteria[2].Value = "0";

                conditionalFormat.FirstFormulaR1C1 = "=R[1]C[0]";
                conditionalFormat.SecondFormulaR1C1 = "=R[1]C[1]";

                //Create icon sets for the data in the specified range.
                conditionalFormats = worksheet.Range["E7:E46"].ConditionalFormats;
                conditionalFormat = conditionalFormats.AddCondition();
                conditionalFormat.FormatType = ExcelCFType.IconSet;
                IIconSet iconSet = conditionalFormat.IconSet;

                //Apply three symbol icons and hide the data in the specified range.
                iconSet.IconSet = ExcelIconSetType.ThreeSymbols;
                iconSet.IconCriteria[1].Type = ConditionValueType.Percent;
                iconSet.IconCriteria[1].Value = "50";
                iconSet.IconCriteria[2].Type = ConditionValueType.Percent;
                iconSet.IconCriteria[2].Value = "50";
                iconSet.ShowIconOnly = true;

                #region Save
                //Save the workbook.
                FileStream outputStream = new FileStream("AdvancedCF.xlsx", FileMode.Create, FileAccess.Write);
                workbook.SaveAs(outputStream);
                #endregion

                //Dispose streams.
                outputStream.Dispose();
                inputStream.Dispose();
            }
        }
    }
}

The output of the above code example looks like the following screenshot.

Excel Spreadsheet with Data Bar, Color Scale, and Icon Set
Excel Spreadsheet with Data Bar, Color Scale, and Icon Set

Note: For more details, refer to the icon sets in .NET Excel Library documentation.

GitHub samples

You can download examples of highlighting data with conditional formatting in C# from this GitHub repository.

Don't settle for ordinary spreadsheet solutions. Switch to Syncfusion and upgrade the way you handle Excel files in your apps!

Conclusion

Syncfusion Excel (XlsIO) Library provides support to highlight Excel data using C#. Take a moment to peruse the documentation where you’ll find other formatting options and features like importing and exporting data, data validation, tables, and charts with accompanying code samples.

Using the Excel Library, you can export Excel data to PDFimagedata tableCSVTSVHTMLcollections of objectsODSJSON, and more file formats.

If you are new to our Excel Library, we highly recommend you follow our getting started guide.

Are you already a Syncfusion user? You can download the product setup here. If you’re not yet a Syncfusion user, you can download a free, 30-day trial here.

Please let us know your thoughts in the comments section below. If you have questions about these features, contact us through our support forumsupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed