How To Apply Cell Text & Background Color In An Excel Sheet Using EPPlus (C#) - Part Two

Apply Excel Cell text color
  • In EPPlus, ExcelRange class has a style property. This style property is the type of ExcelStyle (seal) class.
  • ExcelStyle class has another ExcelFont (seal) type font properties.
  • ExcelFont class has ExcelColor (seal) type colorproperty. ExcelColor has SetColor method. This method can accept Colorstructure object as a parameter.
Example
  • ExcelRange Rng = new ExcelRange();
  • Rng.Style.Font.Color.SetColor(Color.Red);
*By default, EPPlus supports Black font color, if you are not specifying any Font color.

Now, the next question in our mind is how to set cell background color?

Example
  • Rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
  • Rng.Style.Fill.BackgroundColor.SetColor(Color.Green);
  • Here SetColor method can support structure Color property as a parameter.
  • You can also specify the HTML Color code.
*By default, EPPlus supports White background color.

For Example
  • Color DeepBlueHexCode = ColorTranslator.FromHtml("#254061");
  • Rng.Style.Fill.BackgroundColor.SetColor(DeepBlueHexCode);
  • In this example FromHtml() directly accept HTML RGB (Red Green Blue) color Code.
Output on an Excel sheet is given below.



Source code
  1. using OfficeOpenXml;  
  2. using System.IO;  
  3. using System;  
  4. //add two new namespace  
  5. using OfficeOpenXml.Style;  
  6. using System.Drawing;  
  7. class Program {  
  8.     static void Main(string[] args) {  
  9.         ExcelPackage ExcelPkg = new ExcelPackage();  
  10.         ExcelWorksheet wsSheet1 = ExcelPkg.Workbook.Worksheets.Add("Sheet1");  
  11.         using(ExcelRange Rng = wsSheet1.Cells[2, 2, 2, 2]) {  
  12.             Rng.Value = "Welcome to Everyday be coding - tutorials for beginners";  
  13.             Rng.Style.Font.Size = 16;  
  14.             Rng.Style.Font.Bold = true;  
  15.             Rng.Style.Font.Italic = true;  
  16.         }  
  17.         //First Border Box  
  18.         using(ExcelRange Rng = wsSheet1.Cells[5, 2, 8, 4]) {  
  19.             Rng.Value = "Text Color & Background Color";  
  20.             Rng.Merge = true;  
  21.             Rng.Style.Font.Bold = true;  
  22.             Rng.Style.Font.Color.SetColor(Color.Red);  
  23.             Rng.Style.Fill.PatternType = ExcelFillStyle.Solid;  
  24.             Rng.Style.Fill.BackgroundColor.SetColor(Color.LightBlue);  
  25.         }  
  26.         wsSheet1.Protection.IsProtected = false;  
  27.         wsSheet1.Protection.AllowSelectLockedCells = false;  
  28.         ExcelPkg.SaveAs(new FileInfo(@ "D:\New.xlsx"));  
  29.     }  
  30. }  
Now, build & execute the given code. File is (New.xlsx), which is stored on D: drive of the computer.
Thank you for reading this blog. 
Ebook Download
View all
Learn
View all