How to clone Excel Font Style in C#

The colorful excel font makes the whole excel document attractive and it is easy to give more importance to some data we'd like to show to others. With the help of Spire.XLS, developers can easily set Excel font and copy formatting from one place and apply it to another. This article will focus on demonstrating how to clone Excel font style directly when adding the new text to Excel worksheet in C#.

Note: Before Start, please ensure that you have download the latest version of Spire.XLS (V7.8.64 or above) and add Spire.xls.dll in the bin folder as the reference of Visual Studio.

Here comes to the code snippet of how to clone cell style for the text in Excel worksheets.

Step 1: Create a new excel document instance and get the first worksheet.

Workbook book = new Workbook();
Worksheet sheet = book.Worksheets[0];

Step 2: Add the text to the Excel sheet cell range A1.

sheet.Range["A1"].Text = "Text1";

Step 3: Set A1 cell range's CellStyle.

CellStyle style = book.Styles.Add("style");
style.Font.FontName = "Calibri";
style.Font.Color = Color.Red;
style.Font.Size = 12;
style.Font.IsBold = true;
style.Font.IsItalic = true;
sheet.Range["A1"].CellStyleName = style.Name

Step 4: Use the method style.clone() to clone the same style for B2 cell range.

CellStyle csOrieign = style.clone();
sheet.Range["B2"].Text = "Text2";
sheet.Range["B2"].CellStyleName = csOrieign.Name;

Step 5: Clone the same style for C3 cell range and then reset the font color for the text.

CellStyle csGreen = style.clone();
csGreen.Font.Color = Color.Green;
sheet.Range["C3"].Text = "Text3";
sheet.Range["C3"].CellStyleName = csGreen.Name;

Step 6: Save the document to file and set the excel version.

book.SaveToFile("sample2.xlsx", ExcelVersion.Version2010);

Effective screenshots:

How to clone Excel Font Style in C#

Full codes:

using Spire.Xls;
using System.Drawing;
namespace CloneExcelFont
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook book = new Workbook();
            Worksheet sheet = book.Worksheets[0];

            sheet.Range["A1"].Text = "Text1";
            CellStyle style = book.Styles.Add("style");

            style.Font.FontName = "Calibri";
            style.Font.Color = Color.Red;
            style.Font.Size = 12;
            style.Font.IsBold = true;
            style.Font.IsItalic = true;
            sheet.Range["A1"].CellStyleName = style.Name;

            CellStyle csOrieign = style.clone();
            sheet.Range["B2"].Text = "Text2";
            sheet.Range["B2"].CellStyleName = csOrieign.Name;

            CellStyle csGreen = style.clone();
            csGreen.Font.Color = Color.Green;
            sheet.Range["C3"].Text = "Text3";
            sheet.Range["C3"].CellStyleName = csGreen.Name;

            book.SaveToFile("sample2.xlsx", ExcelVersion.Version2010);

        }
    }
}