跳過到頁腳內容
使用 IRONXL

C# 程式化地開啟 Excel 文件(代碼範例教程)

We are all aware that the Excel spreadsheet has been around for a long time. It is primarily used for calculations and graphing data, making it perfect for creating financial models, analyzing the cost-effectiveness of various advertising campaigns, and many other types of analysis.

While it should be a straightforward process, creating an Excel file programmatically can be difficult because of the number of rows and columns involved. Many tasks are quickly done with Excel, such as selecting or sorting data. However, there is no easy way to do it when you need to create a new spreadsheet from scratch. Creating XLSX files programmatically requires many lines of code, something which can get complicated very quickly.

Excel files are harder to create programmatically because they need to be set up with data and formulas before they can be used. The different kinds of data you store in the spreadsheet can significantly impact how difficult it is to create an Excel file. If you need to create an Excel file with a lot of data, you will probably find it more complicated than if there are fewer columns and rows. Secondly, the formatting of your spreadsheet could also make creating an Excel file difficult. For example, suppose you want the columns in your spreadsheet to be aligned at all times. In that case, this will make generating a new spreadsheet more complicated than usual, because you will need to calculate where each column should be, based on other columns in the sheet, and how many rows there should be.

So, we have come up with a solution. We will show how easy it is to create and read Excel files with the IronXL C# library.

IronXL: C# Excel 函式庫

IronXL is a C# Excel library that helps you make more robust spreadsheets. With IronXL, there are no limitations on the number of rows and columns in a spreadsheet. You can have as many rows and columns as you need without adding complex formulas for calculating column widths.

IronXL makes it possible to create workbooks with millions of rows and thousands of columns, which would not be possible without complex calculations or using any other spreadsheet software. With IronXL, there is no limit to the number of rows or columns in your spreadsheet, allowing you to design very high-dimensional models on a single sheet. IronXL is a complete library that will complete all Excel processes. Its fully kitted features will create and read Excel files in C#.

IronXL simplifies the number crunching and data analysis process by providing its users with powerful functions that they can use to work on the data without too much effort. We also do not need to install Microsoft Office on our machine.

The following section will describe how the library can be used to read and write Excel files in C#.

Create a C# .NET Project

Create a new C# Console project in Microsoft Visual Studio. I am using Visual Studio's 2022 version. You can use any version, but the latest version is recommended. When creating a project, choose .NET Framework > 3.0 because it is recommended. You can give any name to your project. You can create a GUI project, too, according to your needs. IronXL supports every template format of the .NET Framework. After completing the project, the next step will be to install the IronXL library.

Install the IronXL Library

Now it's time to install the IronXL library. You must follow the steps below to install it. We will install the library using the NuGet Package Manager.

Go to the Tools option from the main menu bar. Hover on the NuGet Package Manager and select the Manage NuGet Packages for Solution... option from the dropdown menu.

C# Open Excel File Programmatically (Code Example Tutorial), Figure 1: Navigate to NuGet Package Manager in Visual Studio Navigate to NuGet Package Manager in Visual Studio

這將打開 NuGet 套件管理器選項卡。 Go to the browse tab and search for IronXL. Select IronXL from the search results.

C# Open Excel File Programmatically (Code Example Tutorial), Figure 2: Search for IronXL in NuGet Package Manager Search for IronXL in NuGet Package Manager

Install the selected library. You will see the IronXL library dependencies in the solution explorer.

C# Open Excel File Programmatically (Code Example Tutorial), Figure 3: IronXL package is added to the project IronXL package is added to the project

Now we can use the library in our project. Let's move to the program.cs file and write the code for creating an Excel file.

Code for creating Excel Files

Here is the code for creating an Excel file programmatically using the IronXL C# library.

using IronXL;

// Create a new Excel workbook in XLSX format
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

// Create a new worksheet named "example_sheet"
var sheet = workbook.CreateWorkSheet("example_sheet");

// Set value of a single cell
sheet["A1"].Value = "Example";

// Set value to multiple cells in a range
sheet["A2:A4"].Value = 5;

// Change background color of a cell
sheet["A5"].Style.SetBackgroundColor("#f0f0f0");

// Set style (bold font) to multiple cells in a range
sheet["A5:A6"].Style.Font.Bold = true;

// Set formula for cell A6
sheet["A6"].Value = "=SUM(A2:A4)";

// Verify if the value in A6 is the sum of the range A2:A4
if (sheet["A6"].IntValue == sheet["A2:A4"].IntValue)
{
    Console.WriteLine("Basic test passed");
}

// Save the workbook as "example_workbook.xlsx"
workbook.SaveAs("example_workbook.xlsx");
using IronXL;

// Create a new Excel workbook in XLSX format
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

// Create a new worksheet named "example_sheet"
var sheet = workbook.CreateWorkSheet("example_sheet");

// Set value of a single cell
sheet["A1"].Value = "Example";

// Set value to multiple cells in a range
sheet["A2:A4"].Value = 5;

// Change background color of a cell
sheet["A5"].Style.SetBackgroundColor("#f0f0f0");

// Set style (bold font) to multiple cells in a range
sheet["A5:A6"].Style.Font.Bold = true;

// Set formula for cell A6
sheet["A6"].Value = "=SUM(A2:A4)";

// Verify if the value in A6 is the sum of the range A2:A4
if (sheet["A6"].IntValue == sheet["A2:A4"].IntValue)
{
    Console.WriteLine("Basic test passed");
}

// Save the workbook as "example_workbook.xlsx"
workbook.SaveAs("example_workbook.xlsx");
Imports IronXL

' Create a new Excel workbook in XLSX format
Private workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

' Create a new worksheet named "example_sheet"
Private sheet = workbook.CreateWorkSheet("example_sheet")

' Set value of a single cell
Private sheet("A1").Value = "Example"

' Set value to multiple cells in a range
Private sheet("A2:A4").Value = 5

' Change background color of a cell
sheet("A5").Style.SetBackgroundColor("#f0f0f0")

' Set style (bold font) to multiple cells in a range
sheet("A5:A6").Style.Font.Bold = True

' Set formula for cell A6
sheet("A6").Value = "=SUM(A2:A4)"

' Verify if the value in A6 is the sum of the range A2:A4
If sheet("A6").IntValue = sheet("A2:A4").IntValue Then
	Console.WriteLine("Basic test passed")
End If

' Save the workbook as "example_workbook.xlsx"
workbook.SaveAs("example_workbook.xlsx")
$vbLabelText   $csharpLabel

In the following code, we import the IronXL library at the top of our program. We then initiate a WorkBook object to create a new Excel workbook in XLSX format. Next, we create a WorkSheet within the WorkBook using the CreateWorkSheet method, providing the worksheet's name as a parameter. It's possible to create multiple worksheets this way. Now, our Excel workbook and worksheet are ready to use.

Next, we enter data into the cells of the Excel worksheet. Cells can be accessed by their names, and the "Value" property is used to access or set cell values. Styles, such as font size and style, can be set for specific cells or ranges of cells. Formulas can also be defined for individual cells or cell ranges. Finally, we save our Excel file as "example_workbook.xlsx", which will be saved to the debug folder of our project.

輸出

Here you can see the output of the created program.

C# Open Excel File Programmatically (Code Example Tutorial), Figure 4: Result file displayed in Microsoft Excel Result file displayed in Microsoft Excel

結論

We can create, read and modify existing Microsoft Excel files or an XLSX file in C#. IronXL provides many other features for Microsoft Excel files. You can explore these features from our tutorial page. IronXL is the complete package for working with Excel. IronXL also offers a wide range of features to interact with Excel WorkBook, WorkSheet, and Cells level such as converting between popular formats, cell data formatting, inserting math functions, and even managing charts.

IronXL is entirely free for development. You can use it for free in the development phase with the IronXL watermark. IronXL also offers a free trial key for production, allowing you to test it for 30 days, completely free. IronXL has a reasonable pricing plan that you can purchase at a level that matches your requirements.

C# Open Excel File Programmatically (Code Example Tutorial), Figure 5: IronXL pricing plan IronXL pricing plan

What's more - Iron Software currently offers you five software packages for the price of just two.

常見問題解答

我如何使用C#以程式方式開啟Excel文件?

要以程式方式在C#中開啟Excel檔案,可以使用IronXL庫。首先,通過Visual Studio中的NuGet軟體包管理員安裝IronXL。然後,使用WorkBook類別開啟和操作Excel文件,而不需要Microsoft Office。

使用IronXL進行Excel文件操作有哪些好處?

IronXL通過提供強大的功能來簡化C#中的Excel文件操作,包括讀取、創建和修改Excel文件。它支持大型數據集,並提供格式化、公式計算以及匯出到不同格式的功能。

我可以使用C#創建包含大型數據集的Excel文件嗎?

是的,IronXL允許您創建包含數百萬行和數千列的Excel文件,非常適合以程式方式處理大型數據集和高維模型。

我應該遵循哪些步驟在C#項目中設置IronXL?

要在C#項目中設置IronXL,打開Visual Studio,轉到工具 > NuGet包管理器 > 管理NuGet套件以解決方案,搜索IronXL,然後安裝它。這將把庫集成到您的項目中,用於處理Excel文件。

如何使用IronXL以程式方式格式化Excel儲存格?

使用IronXL,您可以以程式方式格式化Excel儲存格,設置值、樣式和公式。您可以調整背景顏色、應用不同的字體樣式,並在您的C#代碼中直接使用Excel公式。

在C#中操作Excel文件是否需要Microsoft Office?

不,IronXL在C#中處理Excel文件不需要Microsoft Office。它單獨操作,允許您創建、讀取和編輯Excel文件而不需要其他軟件。

我如何使用C#將Excel文件轉換為其他格式?

IronXL允許您將Excel文件轉換為其他格式,如CSV。這是通過其匯出功能實現的,允許不同試算表文件類型之間的無縫轉換。

IronXL有哪些授權選項可用?

IronXL為開發提供帶有浮水印的免費試用版。對於生產用途,提供免費30天試用鍵,還有不同的定價計劃以滿足不同用戶的需求。

哪些.NET版本與IronXL兼容?

IronXL支持多個.NET框架版本,包括.NET Framework 3.0及以上版本。建議使用最新版本的Visual Studio以獲得最佳兼容性和性能。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。