How to Format Fonts in Excel in C#

·

2 min read

In Excel, fonts play a crucial role in formatting and presenting data. Utilizing fonts of the appropriate style, size, or color can enhance the appearance and functionality of Excel spreadsheets, improving user experience. This article is going to share how to programmatically apply different font styles in Excel cells using a free .NET Excel library.

Install the Free Library

First, we need to download the free library - Free Spire.XLS for .NET via the link below or install it directly via Nuget.

https://www.e-iceblue.com/Download/download-excel-for-net-free.html

Set Excel Font Style Using C#.

The free Excel library allows us to set or change the font name, color, size and style in cells. Below is the sample C# code.

using Spire.Xls;
using System.Drawing;

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

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

            //Set font name
            sheet.Range["B1"].Value = "Font Name: Arial Black";
            sheet.Range["B1"].Style.Font.FontName = "Arial Black";

            //Set font size
            sheet.Range["B2"].Value = "Font Size: 18";
            sheet.Range["B2"].Style.Font.Size = 18;

            //Set font color 
            sheet.Range["B3"].Value = "Font Color: Red";
            sheet.Range["B3"].Style.Font.Color = Color.Red;

            //Make text bold
            sheet.Range["B4"].Value = "Font Style: Bold";
            sheet.Range["B4"].Style.Font.IsBold = true;

            //Make text italic 
            sheet.Range["B5"].Value = "Font Style: Italic";
            sheet.Range["B5"].Style.Font.IsItalic = true;

            //Underline text
            sheet.Range["B6"].Value = "Font Style: Underline";
            sheet.Range["B6"].Style.Font.Underline = FontUnderlineType.Single;

            //Strikethrough text 
            sheet.Range["B7"].Value = "Font Style: Strikethrough ";
            sheet.Range["B7"].Style.Font.IsStrikethrough = true;

            //Set column width and row height
            sheet.AllocatedRange.AutoFitColumns();
            sheet.AllocatedRange.RowHeight = 18;

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


With the free Excel library, we can also use different fonts style in a single cell to emphasize some specific characters. Besides, other Excel document processing & conversion functions can be implemented.

https://www.e-iceblue.com/Tutorials/Spire.XLS/Spire.XLS-Program-Guide/Spire.XLS-Program-Guide-Content.html