News Category

C#/VB.NET: Set Background Color and Pattern for Excel Cells

2022-04-07 07:49:00 Written by  Administrator
Rate this item
(0 votes)

By default, the cells in an Excel document are formatted with a background color of transparent. When you need to emphasize some important data in particular cells, Microsoft Excel provides the "Fill Color" formatting option to change the background color or pattern style of the cells. In this article, you will learn how to programmatically set background color and pattern style for a specified cell or cell range in Excel using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Set Background Color and Pattern for Excel Cells

The detailed steps are as follows.

  • Instantiate a Workbook object.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[] property.
  • Get a specified cell range using Worksheet.Range[] property.
  • Get the style of the specified cell range using CellRange.Style property.
  • Set the background color for the specified cell range using CellStyle.Color property.
  • Set the fill pattern style for the specified cell range using CellStyle.FillPattern property.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using System.Drawing;
using Spire.Xls;

namespace CellBackground
{
    class Program
    {
        static void Main(string[] args)
        {
            //Instantiate a Workbook object
            Workbook workbook = new Workbook();

            //Load a sample Excel file
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\data.xlsx");

            //Get the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            //Set background color for Range ["A1:E1"] and ["A2:A10"]
            worksheet.Range["A1:E1"].Style.Color = Color.MediumSeaGreen;
            worksheet.Range["A2:A10"].Style.Color = Color.LightYellow;

            //Set background color for cell E6
            worksheet.Range["E6"].Style.Color = Color.Red;

            //Set pattern style for Range ["B4:D5"]
            worksheet.Range["B4:D5"].Style.FillPattern = ExcelPatternType.Percent125Gray;

            //Save the result file 
            workbook.SaveToFile("CellBackground.xlsx", ExcelVersion.Version2013);
        }

    }
}

C#/VB.NET: Set Background Color and Pattern for Excel Cells

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Thursday, 07 April 2022 07:41