跳至页脚内容
使用 IRONXL

如何在 C# 中使用 Excel 字体样式

One of the most effective programs for manipulating and visualizing data is still Microsoft Excel. Its adaptability includes the ability to structure and customize data to meet individual needs, in addition to its extensive feature set. To improve data presentation and make it more legible and visually appealing, font styles are essential. A common way to manipulate font styles with Excel in C# is using the Font property utilizing Microsoft.Office.Interop.Excel. However, this option isn't as flexible or convenient as alternative solutions. Hence, this post will discuss using IronXL, on how to use C# Excel to set font style.

How to Use C# Excel Font Style

  1. Open or create a project in C#.
  2. Use NuGet to install the IronXL library.
  3. Use the IronXL namespace in your C# program.
  4. Load an Excel file using var workbook = WorkBook.Load("example.xlsx");.
  5. Select a worksheet using var sheet = workbook.WorkSheets[0];.
  6. Define a range of cells using var range = sheet["A1:B2"];.
  7. Set font properties such as style using range.Style.Font.Name = "Calibri";, font size with range.Style.Font.Size = 12;, color with range.Style.Font.Color = "#FF0000";, and other properties like range.Style.Font.Bold = true; and range.Style.Font.Italic = true;.
  8. Preserve the worksheet by saving it as "sample.xlsx" using the SaveAs() method.

IronXL

Before diving into Excel font styles, let's quickly introduce IronXL. IronXL is a popular C# library that allows you to create, read, and manipulate Excel files within C# applications easily. It offers a user-friendly API for working with Excel files, making tasks like reading, writing, and formatting data significantly more accessible.

Developers can utilize IronXL to automate Excel-related processes using C#. For C# developers looking to interact with Excel files programmatically, its user-friendly interface and comprehensive documentation make it the go-to option.

Some of IronXL's key characteristics are listed below:

  • Excel File Creation & Editing: IronXL facilitates the creation and editing of Excel files, enabling you to start from scratch and make changes to preexisting ones. Worksheets, rows, columns, and cells can all be programmatically added, removed, or altered.
  • Excel File Reading: It has strong functionality for reading data from Excel files. Effective data processing and analysis are made possible by the simplicity with which cell values, formulas, formatting, and other metadata may be extracted.
  • Writing to Excel Files: IronXL provides easy support for writing data to Excel files. It is perfect for creating reports, exporting data, and automating data input jobs since it allows you to fill cells with values, formulas, and formatting.
  • Formatting and Style: The library provides extensive assistance with the formatting and styling of Excel documents. Spreadsheets can be made to look professional and eye-catching by adjusting font styles, colors, borders, alignment, and other aspects.
  • Formula Support: You can use IronXL to work programmatically with Excel formulas. Formula dependencies can be easily handled, values can be calculated, and formulae can be specified for specific cells.
  • Chart Creation: It lets you make graphs and charts inside Excel documents. For an effective visual representation of data and patterns, you can create a variety of chart formats, such as pie charts, bar charts, and line charts.
  • Data Validation: You can set rules and limitations for cell values using IronXL's data validation tools. To guarantee data correctness and integrity, you can validate input using criteria like range, list, date, and custom formulas.
  • Protection and Encryption: Excel files can be password-protected and encrypted using the capability provided by the library. To protect your documents from unwanted access, you can set permissions, restrict access, and encrypt important data.
  • Integration with .NET apps: IronXL offers C# developers a recognizable and user-friendly programming interface with its smooth integration with .NET applications. Its extensive feature set and comprehensive set of APIs are easy to integrate into your current .NET applications.

IronXL is a feature-rich and adaptable C# library for manipulating Excel that provides a multitude of options to help you simplify your activities connected to Excel. IronXL offers the features and tools you need to be successful, whether you're building data-driven applications, analyzing data, or producing reports. Refer to the documentation here to learn more.

Creating a New Project in Visual Studio

To open the Visual Studio application, select File from the File menu. After selecting "New Project," select "Console application."

How to Use C# Excel Font Style: Figure 1 - The Visual Studio Application page

After choosing the file location, type the project name into the assigned text field. Subsequently, pick the required .NET Framework by clicking the Create button, as demonstrated in the sample below.

How to Use C# Excel Font Style: Figure 2 - The Visual Studio Application page: Enter the desired project name

The Visual Studio project's organization will then depend on the selected application. To add code and construct the application, just open the program.cs file. The internet application, Windows, or console can all be used.

How to Use C# Excel Font Style: Figure 3 - Select the corresponding frameworks for your project

The code can then be tested and the library added.

Installing IronXL Library

The following patch requires the installation of the IronXL library. Finally, launch the NuGet Package Manager Console and use the following command to complete the installation.

Install-Package IronXL.Excel

How to Use C# Excel Font Style: Figure 4 - Opening the NuGet Package Manager console and enter the installation command

An alternative would be to use the NuGet Package Manager to search for the package "IronXL". We may choose which of the NuGet packages associated with IronXL have to be downloaded from this list of all of them.

How to Use C# Excel Font Style: Figure 5 - Searching and installing IronXL using the browse feature from NuGet Package Manager

Excel font style using IronXL

To begin, allow me to demonstrate how to set font characteristics for a range of cells in a basic way:

using IronXL;

class Program
{
    static void Main(string [] args)
    {
        // Load the existing Excel workbook
        WorkBook workbook = WorkBook.Load("Demo.xlsx");

        // Select the first worksheet
        WorkSheet sheet = workbook.WorkSheets[0];

        // Define the range of cells
        var range = sheet["A1:B2"];

        // Set font characteristics for the range of cells
        range.Style.Font.Name = "Calibri";  // Font name
        range.Style.Font.Size = 12;         // Font size
        range.Style.Font.Color = "#FF0000"; // Font color
        range.Style.Font.Bold = true;       // Bold font
        range.Style.Font.Italic = true;     // Italicized font

        // Save the modified workbook as a new file
        workbook.SaveAs("Sample.xlsx");
    }
}
using IronXL;

class Program
{
    static void Main(string [] args)
    {
        // Load the existing Excel workbook
        WorkBook workbook = WorkBook.Load("Demo.xlsx");

        // Select the first worksheet
        WorkSheet sheet = workbook.WorkSheets[0];

        // Define the range of cells
        var range = sheet["A1:B2"];

        // Set font characteristics for the range of cells
        range.Style.Font.Name = "Calibri";  // Font name
        range.Style.Font.Size = 12;         // Font size
        range.Style.Font.Color = "#FF0000"; // Font color
        range.Style.Font.Bold = true;       // Bold font
        range.Style.Font.Italic = true;     // Italicized font

        // Save the modified workbook as a new file
        workbook.SaveAs("Sample.xlsx");
    }
}
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the existing Excel workbook
		Dim workbook As WorkBook = WorkBook.Load("Demo.xlsx")

		' Select the first worksheet
		Dim sheet As WorkSheet = workbook.WorkSheets(0)

		' Define the range of cells
		Dim range = sheet("A1:B2")

		' Set font characteristics for the range of cells
		range.Style.Font.Name = "Calibri" ' Font name
		range.Style.Font.Size = 12 ' Font size
		range.Style.Font.Color = "#FF0000" ' Font color
		range.Style.Font.Bold = True ' Bold font
		range.Style.Font.Italic = True ' Italicized font

		' Save the modified workbook as a new file
		workbook.SaveAs("Sample.xlsx")
	End Sub
End Class
$vbLabelText   $csharpLabel

The Excel file "Demo.xlsx" is being loaded into the WorkBook object first. It will create a new file with this name if the current one doesn't exist. In this case, we are choosing the workbook's first worksheet (WorkSheet). If the workbook has more than one sheet, you can select a particular sheet by name or index. Within the chosen Excel worksheet, we designate a range of cells from cell A1 to cell B2. This enables us to set font styles for this particular cell range.

For the chosen range of cells, these lines set the following font object properties:

  • Font.Name: Defines the font type (Calibri).
  • Font.Size: Sets the font size.
  • Font.Color: Changes the font color to red (#FF0000 in hexadecimal).
  • Font.Bold: Makes the text bold.
  • Font.Italic: Apply italics to the text.

Lastly, we save the altered worksheet to a new file called "Sample.xlsx" after applying the font styles. Below is the output generated from the above code.

Setting Font Name

An IFont interface that exposes the FontName field is given via the Style property. You can specify the preferred font name for the cell using this parameter.

// Select the range of cells
var fontrange = sheet["A1:B1"];
fontrange.Style.Font.Name = "Calibri"; // Set font name
// Select the range of cells
var fontrange = sheet["A1:B1"];
fontrange.Style.Font.Name = "Calibri"; // Set font name
' Select the range of cells
Dim fontrange = sheet("A1:B1")
fontrange.Style.Font.Name = "Calibri" ' Set font name
$vbLabelText   $csharpLabel

How to Use C# Excel Font Style: Figure 6 - Code example changing the font style programmatically

Setting Font Color

An IFont interface that exposes the Color property is given by the Style property. You can use a hex code string to set the font color with this property. Six hexadecimal digits are used to define colors in hex codes (e.g., #FF0000 for red, #00FFFF for cyan). To obtain the proper hex code for the color of your typeface, there are numerous color pickers available online.

// Select the range of cells
var fontrange = sheet["A1:B1"];
fontrange.Style.Font.Color = "#FF0000"; // Set font color
// Select the range of cells
var fontrange = sheet["A1:B1"];
fontrange.Style.Font.Color = "#FF0000"; // Set font color
' Select the range of cells
Dim fontrange = sheet("A1:B1")
fontrange.Style.Font.Color = "#FF0000" ' Set font color
$vbLabelText   $csharpLabel

How to Use C# Excel Font Style: Figure 7 - Code example changing the font color programmatically

Setting Font Bold

The Bold property is exposed through the IFontFormatting interface that is provided by the Style property. The font's boldness is set by this attribute, which is a boolean value. To make the typeface bold in the selected cell, set the Bold property to true.

// Select the range of cells
var fontrange = sheet["A1:B1"];
fontrange.Style.Font.Bold = true; // Set font to bold
// Select the range of cells
var fontrange = sheet["A1:B1"];
fontrange.Style.Font.Bold = true; // Set font to bold
' Select the range of cells
Dim fontrange = sheet("A1:B1")
fontrange.Style.Font.Bold = True ' Set font to bold
$vbLabelText   $csharpLabel

How to Use C# Excel Font Style: Figure 8 - Code example changing the font to Bold programmatically

Setting Font Italic

The Italic property is exposed through the IFontFormatting interface that is provided by the Style property. This property, which is a boolean value, controls whether or not the typeface is italic. To make the font italic in the selected cell, set the Italic property to true.

// Select the range of cells
var fontrange = sheet["A1:B1"];
fontrange.Style.Font.Italic = true; // Set font to italic
// Select the range of cells
var fontrange = sheet["A1:B1"];
fontrange.Style.Font.Italic = true; // Set font to italic
' Select the range of cells
Dim fontrange = sheet("A1:B1")
fontrange.Style.Font.Italic = True ' Set font to italic
$vbLabelText   $csharpLabel

How to Use C# Excel Font Style: Figure 9 - Code example changing the font to Italic programmatically

The above list of codes shows you how to use IronXL to programmatically change the font styles in Excel using C#. You may quickly alter how text appears in Excel spreadsheets by loading an existing workbook, choosing a worksheet, specifying a range of cells, and adjusting font attributes. Although not shown above, you can also similarly modify the font size for a specific cell or the entire worksheet, for a list of attributes regarding the interface IFont refer to here, and to know more about the code example refer to here.

Conclusion

Excel spreadsheet readability and visual appeal are greatly improved by the use of font styles. Programmatically changing font styles becomes simple and scalable when using C# and IronXL. If you need to apply styles to specific cells or format large ranges of cells, whether you're creating a new workbook or editing an existing one, IronXL offers an extensive toolkit to fulfill your needs.

By mastering Excel font styles using C# and IronXL, you can create professional-looking spreadsheets that effectively communicate your data and insights. A refined and powerful user experience may be achieved by careful consideration of font styling, whether you're creating dashboards, reports, or data-driven applications.

When it comes to processing and presenting data, the options are endless. Having IronXL in your toolbox gives you the ability to manage a variety of activities linked to Excel in your C# programs. When ready to commit, users can start using IronXL for free. Check here to learn more about the Iron software product.

常见问题解答

如何在 C# 中使用 Excel 设置字体样式而不使用 Interop?

您可以使用 IronXL 在 C# 中设置 Excel 的字体样式,而无需依赖 Microsoft.Office.Interop.Excel。IronXL 提供了简单的方法来修改字体属性,如名称、大小、颜色、一种更加灵活和方便的方式来加粗和使用斜体。

安装 IronXL 以在 C# 中操作 Excel 的步骤有哪些?

要在 C# 项目中安装 IronXL,请使用 NuGet 包管理器。在包管理器控制台中运行命令 Install-Package IronXL.Excel,或者在 NuGet 包管理器 UI 中搜索 'IronXL' 并从那里安装。

IronXL 可以用来对 Excel 单元格范围应用字体样式吗?

是的,IronXL 允许您对 Excel 工作表中的特定单元格范围应用字体样式。您可以使用 IronXL 的 range.Style.Font 属性修改字体属性,例如名称、大小、颜色、粗体和斜体。

如何使用 C# 更改 Excel 表中的字体大小?

使用 IronXL,您可以通过设置您在 C# 应用程序中所需的单元格范围的 range.Style.Font.Size 属性来更改 Excel 表中的字体大小。

可以创建 Excel 文件并使用 IronXL 设置字体样式吗?

是的,IronXL 使您可以创建新的 Excel 文件并为这些文件中的单元格设置字体样式。您可以定义字体属性,例如名称、大小、颜色、突出显示和斜体,以增强数据的可读性和视觉吸引力。

使用 IronXL 操作 Excel 在 C# 中比使用 Interop 有什么好处?

IronXL 提供了一个比 Interop 更用户友好的 API,避免 Excel 必须安装在服务器上。它简化了诸如设置字体样式、数据读写等任务,并提供了其他功能,诸如数据验证和图表创建。

如何保存使用 IronXL 对 Excel 文件所做的更改?

使用 IronXL 修改 Excel 文件后,您可以通过使用 workbook.SaveAs('filename.xlsx') 方法保存您的更改,从而确保您的更新是保留的。

IronXL 可以集成进 .NET 应用程序用于操作 Excel 文件吗?

是的,IronXL 可以无缝集成到 .NET 应用程序中,提供了一个强大的 API 用于操作 Excel 文件,使其成为开发人员在 .NET 框架中工作的理想选择。

在哪里可以找到有关使用 IronXL 操作 Excel 的详细文档?

IronXL 的官方文档包含有关各种功能(例如字体样式)教程和示例,可在 IronXL 官方网站上找到。此资源可以指导您在 C# 项目中实现不同的功能。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。