[solved] C# how to change the color of windows excel-sheet cells background color and forecolor

Problem A

An issue with the Windows c# excel sheet cell font style not changing to ‘black’ color

Problem B

Highlighting import columns header in an excel sheet using c# winforms

excel cell color change
excel cell color change

Solution

The Microsoft.Office.Interop.Excel package allows us to access the excel to API objects.

In solution Explorer, Right click on project name and choose “Manage Nuget packages” option to Add new Microsoft.Office.Interop.Excel  new package by Microsoft then click OK, if you have not installed yet.

Microsoft.Office.Interop.Excel

The ClosedXML package allows us to access the excel to API objects.

In solution Explorer, Right click on project name and choose “Manage Nuget packages” option to Add new ClosedXML new package by Microsoft then click OK, if you have not installed yet.

ClosedXML
ClosedXML

Do copy paste the below code

using ClosedXML.Excel;
using System;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //path of the excel file present
            string filePath = @"C:\Users\Book1.xlsx";
            var workbook = new XLWorkbook(filePath);
            // The most important columns are highlighted in Client Deliverable Variable Pivot Report  
            IXLWorksheet ws = workbook.Worksheets.First();
            for (int col = 1; col <= 5; col++)
            {
                string columnName = ws.Cell(1, col).Value.ToString();
                if (columnName == "col1" || columnName == "col5" || columnName == "col7")
                {
                    ws.Cell(1, col).Style.Fill.BackgroundColor = XLColor.Yellow;
                    ws.Cell(1, col).Style.Font.FontColor = XLColor.FromTheme(XLThemeColor.Text1);
                    ws.Cell(1, col).Style.Font.SetBold();
                }
            }
            workbook.SaveAs(filePath);
            try
            {
                if (workbook != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                    workbook = null;
                }
            }
            catch (Exception)
            {
            }
            GC.Collect();
        }
    }
}

Conclusion

The Microsoft.Office.Interop.Excel package allows us access excel objects and change the behaviour of the cells style. XLColor.FromTheme(XLThemeColor.Text1); can be used set the cell text font color style as black.

Shivaraju M
Shivaraju M

Over 3+ years experience in IT industry, good knowledge in . Net-based Web applications, windows applications, web services, and SPAs. I have played
multiple roles related to technical delivery in multiple domains while working on over 10+ technologies. I am
currently focused on continuous improvement and agile project management.

Leave a Reply