跳至页脚内容
使用 IRONXL

如何在 C# 中创建新的 Excel 工作簿

Microsoft Excel is one of the most universal tools for data manipulation and analysis across various industries. In many software projects, there's often a requirement to programmatically engage with Excel files. This could involve tasks such as report generation, managing data imports or exports, or automating specific processes.

In the C# programming language ecosystem, IronXL stands out as a robust library for Excel file manipulation. Whether you're a developer working on a web application, desktop software, or any other C# project, IronXL provides an easy-to-use interface for working with Excel files seamlessly.

How to Create a new Excel Workbook in C#

In this tutorial, we'll learn the process of creating a new workbook using IronXL in C#. We'll walk through the necessary steps, from setting up your development environment to writing the code that generates a new Excel workbook.

By the end of this tutorial, you'll have a solid understanding of how to leverage IronXL to create Excel workbooks programmatically, empowering you to integrate Excel functionality into your C# applications with ease. Let's get started!

What is IronXL?

IronXL is a versatile C# library that allows you to work with Excel documents without the need for Microsoft Office Excel Interop or any Excel Application. It lets you easily read, create, and modify workbooks, format cells, add formulas, and work with both modern and older Excel file formats.

You can validate data, insert images, apply conditional formatting, and create charts without needing Microsoft Office. Developers can build Excel solutions for tasks like financial reports, data dashboards, and inventory management with ease by using IronXL.

Let's begin creating an Excel file in C#.

Step 1: Create a New C# Project

Open Visual Studio and create a new C# Console Application project. Name it as per your preference. You can also create other types of Projects such as ASP.NET MVC, Blazor, MAUI, WEB Forms, Windows Forms, WEB API, etc. This code will work with all project types. I am creating a console application for simplicity and making it relevant for all project types.

Step 2: Install IronXL NuGet Package

To install the IronXL package in your C# project, you can use any of the following ways:

  1. To install IronXL, right-click on your project in Solution Explorer, choose "Manage NuGet Packages," search for IronXL, and then proceed with the installation.

How to Create a new Excel Workbook in C#: Figure 1 - Install IronXL using the Manage NuGet Package for Solution by searching IronXL in the search bar of NuGet Package Manager, then select the project and click on the Install button.

  1. Alternatively, you can install IronXL via the Package Manager Console using the following command:
Install-Package IronXL.Excel

This command will download, install, and add an assembly reference to our project. Wait for the package to be downloaded and installed. Once the installation is complete, you can start using IronXL in your project to work with Excel files programmatically.

How to Create a new Excel Workbook in C#: Figure 2 - Install IronXL using Package Manager Console command: Install-Package IronXL.Excel

Step 3: Import Necessary Namespace

At the top of your C# file, add the following namespace:

using IronXL;
using IronXL;
Imports IronXL
$vbLabelText   $csharpLabel

Step 4: Create a New Excel File

Now, let's write the code to create an Excel file:

internal class Program
{
    static void Main(string[] args)
    {
        // Create a new workbook in the XLSX format
        WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
        workBook.Metadata.Author = "Mr. Author"; // Set the author (optional)

        // Add a blank worksheet named "Sheet1"
        WorkSheet workSheet = workBook.CreateWorkSheet("Sheet1");

        // Add data to the new worksheet
        workSheet["A1"].Value = "Developer Name";
        workSheet["A2"].Value = "John Grahm";
        workSheet["A3"].Value = "David Smith";
        workSheet["A4"].Value = "Rishi Kelkar";

        // Save the Excel file as "Developers.xlsx"
        workBook.SaveAs("Developers.xlsx");
    }
}
internal class Program
{
    static void Main(string[] args)
    {
        // Create a new workbook in the XLSX format
        WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
        workBook.Metadata.Author = "Mr. Author"; // Set the author (optional)

        // Add a blank worksheet named "Sheet1"
        WorkSheet workSheet = workBook.CreateWorkSheet("Sheet1");

        // Add data to the new worksheet
        workSheet["A1"].Value = "Developer Name";
        workSheet["A2"].Value = "John Grahm";
        workSheet["A3"].Value = "David Smith";
        workSheet["A4"].Value = "Rishi Kelkar";

        // Save the Excel file as "Developers.xlsx"
        workBook.SaveAs("Developers.xlsx");
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create a new workbook in the XLSX format
		Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
		workBook.Metadata.Author = "Mr. Author" ' Set the author (optional)

		' Add a blank worksheet named "Sheet1"
		Dim workSheet As WorkSheet = workBook.CreateWorkSheet("Sheet1")

		' Add data to the new worksheet
		workSheet("A1").Value = "Developer Name"
		workSheet("A2").Value = "John Grahm"
		workSheet("A3").Value = "David Smith"
		workSheet("A4").Value = "Rishi Kelkar"

		' Save the Excel file as "Developers.xlsx"
		workBook.SaveAs("Developers.xlsx")
	End Sub
End Class
$vbLabelText   $csharpLabel

The above code demonstrates how to create an Excel file programmatically using IronXL in C#. It starts by creating a new Excel workbook (a new instance of an Excel file) in the XLSX format, sets author metadata, adds a blank Excel worksheet with the name "Sheet1" using the CreateWorkSheet() method, populates data in cells A1 to A4, and finally saves the workbook as "Developers.xlsx".

IronXL offers a range of functionalities for working with Excel files, including creation, manipulation, and saving in various formats like XLSX, CSV, TSV, JSON, XML, and HTML.

The output is as:

How to Create a new Excel Workbook in C#: Figure 3 - Output: Developers.xlsx

Step 5: Formatting and Styling Excel File

IronXL allows you to format cells, apply font styles, set background colors, and adjust alignment. You can create professional-looking spreadsheets by customizing cell appearance.

// Set style of heading for cell A1
workSheet["A1"].Style.BackgroundColor = "#FFFF66"; // Light yellow background
workSheet["A1"].Style.Font.Bold = true; // Bold font

// Set border style for a specific range (A1:A4)
var range = workSheet["A1:A4"];
range.Style.BottomBorder.Type = BorderType.Medium; // Medium bottom border
range.Style.LeftBorder.Type = BorderType.Medium; // Medium left border
range.Style.RightBorder.Type = BorderType.Medium; // Medium right border
range.Style.TopBorder.Type = BorderType.Medium; // Medium top border
// Set style of heading for cell A1
workSheet["A1"].Style.BackgroundColor = "#FFFF66"; // Light yellow background
workSheet["A1"].Style.Font.Bold = true; // Bold font

// Set border style for a specific range (A1:A4)
var range = workSheet["A1:A4"];
range.Style.BottomBorder.Type = BorderType.Medium; // Medium bottom border
range.Style.LeftBorder.Type = BorderType.Medium; // Medium left border
range.Style.RightBorder.Type = BorderType.Medium; // Medium right border
range.Style.TopBorder.Type = BorderType.Medium; // Medium top border
' Set style of heading for cell A1
workSheet("A1").Style.BackgroundColor = "#FFFF66" ' Light yellow background
workSheet("A1").Style.Font.Bold = True ' Bold font

' Set border style for a specific range (A1:A4)
Dim range = workSheet("A1:A4")
range.Style.BottomBorder.Type = BorderType.Medium ' Medium bottom border
range.Style.LeftBorder.Type = BorderType.Medium ' Medium left border
range.Style.RightBorder.Type = BorderType.Medium ' Medium right border
range.Style.TopBorder.Type = BorderType.Medium ' Medium top border
$vbLabelText   $csharpLabel

The above code demonstrates how to customize the appearance of specific cells in an Excel worksheet using IronXL in C#. It first sets the background color of cell A1 to a light yellow shade and makes the font bold, effectively styling it as a heading.

Next, it defines a range spanning cells A1 to A4 and sets medium-weight borders along the bottom, left, right, and top edges of this range, enhancing its visual distinction within the worksheet. These styling options allow developers to create visually appealing and organized Excel documents tailored to their specific needs.

The output is as:

How to Create a new Excel Workbook in C#: Figure 4 - Generate Excel with formatting and styling using IronXL.

Step 6: Formula and Calculation

You can add formulas to cells programmatically. IronXL supports a wide range of Excel functions.

// Add a new column to display the length of developer names
workSheet["B1"].Value = "Name Length";
workSheet["B1"].Style.BackgroundColor = "#FFFF66"; // Styled as heading
workSheet["B1"].Style.Font.Bold = true; // Bold font

// Formula to calculate the length of names in column B
workSheet["B2"].Value = "=LEN(A2)";
workSheet["B3"].Value = "=LEN(A3)";
workSheet["B4"].Value = "=LEN(A4)";

// Add a total count of the length of names in cell A5
workSheet["A5"].Value = "Sum of Length";
workSheet["B5"].Formula = "=SUM(B2:B4)";
// Add a new column to display the length of developer names
workSheet["B1"].Value = "Name Length";
workSheet["B1"].Style.BackgroundColor = "#FFFF66"; // Styled as heading
workSheet["B1"].Style.Font.Bold = true; // Bold font

// Formula to calculate the length of names in column B
workSheet["B2"].Value = "=LEN(A2)";
workSheet["B3"].Value = "=LEN(A3)";
workSheet["B4"].Value = "=LEN(A4)";

// Add a total count of the length of names in cell A5
workSheet["A5"].Value = "Sum of Length";
workSheet["B5"].Formula = "=SUM(B2:B4)";
' Add a new column to display the length of developer names
workSheet("B1").Value = "Name Length"
workSheet("B1").Style.BackgroundColor = "#FFFF66" ' Styled as heading
workSheet("B1").Style.Font.Bold = True ' Bold font

' Formula to calculate the length of names in column B
workSheet("B2").Value = "=LEN(A2)"
workSheet("B3").Value = "=LEN(A3)"
workSheet("B4").Value = "=LEN(A4)"

' Add a total count of the length of names in cell A5
workSheet("A5").Value = "Sum of Length"
workSheet("B5").Formula = "=SUM(B2:B4)"
$vbLabelText   $csharpLabel

The above code illustrates the utilization of formulas and functions in IronXL for calculating the length of developer names and computing the sum of these lengths within an Excel worksheet. Through this demonstration, developers can understand how to integrate formulas and functions within IronXL to perform dynamic calculations and manipulations within Excel worksheets programmatically, offering flexibility and automation in data processing tasks.

Firstly, a header titled "Name Length" is added to cell B1, with styling to highlight its significance. Subsequently, formulas are applied to cells B2, B3, and B4 to calculate the length of each developer's name using the LEN function, referencing the corresponding cell in column A. This enables automatic calculation of name lengths as the developer names change.

Additionally, a total count of developers' name lengths is computed in cell B5 using the SUM function, which adds up the values from cells B2 to B4.

By incorporating these formulas, the worksheet becomes dynamically updated. This use case might not be practical, but this is just for an example of using an Excel formula in code.

How to Create a new Excel Workbook in C#: Figure 5 - Excel output with formula and calculation using IronXL.

Conclusion

In summary, this tutorial has demonstrated the process of creating a new Excel workbook in C# using IronXL, a robust library facilitating Excel file manipulation within the C# ecosystem. With IronXL, developers can seamlessly integrate Excel functionality into their applications, from setting up the development environment to generating Excel workbooks programmatically. Alongside its ability to perform tasks like formatting, styling, and applying formulas, IronXL offers a comprehensive feature set for efficient data management and analysis.

For references on how to use IronXL, please visit the documentation page. IronXL also offers a collection of code examples that are helpful to get started.

Developers can explore IronXL through its free trial and purchase, ensuring a seamless transition from evaluation to full-scale implementation. For more details on perpetual licenses, please visit the license page link.

常见问题解答

如何在 C# 中创建一个不使用 Interop 的新 Excel 工作簿?

您可以通过使用 IronXL 在 C# 中创建一个不使用 Interop 的新 Excel 工作簿。首先,设定您的 C# 项目并安装 IronXL NuGet 包。然后,使用 IronXL 的 API 创建新工作簿,添加工作表,并用数据填充它们。

如何在 C# 中格式化 Excel 工作簿中的单元格?

使用 IronXL,您可以在 C# 中格式化 Excel 工作簿中的单元格。IronXL 允许您通过编程方式应用样式,如字体更改、背景颜色和边框,使您能够创建具有专业外观的电子表格。

我可以在用 C# 创建的 Excel 工作簿中使用公式吗?

是的,您可以在用 C# 创建的 Excel 工作簿中使用公式,使用 IronXL。IronXL 支持多种 Excel 功能,允许您直接在工作表中进行诸如求和列或查找平均值等计算。

与微软 Office Interop 相比,使用 IronXL 有什么优势?

IronXL 提供了几项优于微软 Office Interop 的优势,包括不需要在服务器上安装 Excel、更快的性能以及更容易集成到 C# 应用程序中。它还支持广泛的 Excel 功能,而不需要 Interop 的开销。

如何在 C# 项目中安装 IronXL?

要在 C# 项目中安装 IronXL,访问 Visual Studio 中的 '管理 NuGet 包' 选项,搜索 IronXL 并安装它。或者,使用 Package Manager 控制台输入命令 Install-Package IronXL.Excel

IronXL 可以在网络应用程序中使用吗?

是的,IronXL 可以在 ASP.NET MVC 和 Blazor 等网络应用程序中使用。其灵活性使您能够将 Excel 功能集成到各种项目类型中,包括 Web 窗体和 API。

IronXL 可以处理哪些文件格式?

IronXL 支持多种文件格式,包括 XLSX、CSV、TSV、JSON、XML 和 HTML。这种灵活性使您能够在 Excel 相关任务中轻松处理不同的数据格式。

IronXL 如何协助自动化 Excel 进程?

IronXL 通过允许开发人员在 C# 应用程序中以编程方式创建、修改和管理 Excel 文件来帮助自动化 Excel 进程。这包括生成报告、导入/导出数据和自动化计算。

我在哪里可以访问 IronXL 的文档和教程?

IronXL 的文档和教程可以在 IronXL 网站上找到。这些资源提供了详细的指南和示例,以帮助您在项目中有效地使用 IronXL 的功能。

IronXL 有免费试用吗?

是的,IronXL 提供免费试用版,供开发人员探索其功能。此试用版允许您评估 IronXL 在以编程方式创建和管理 Excel 工作簿方面的能力。

Curtis Chau
技术作家

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

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