跳至页脚内容
使用 IRONXL

如何在 C# 中打开 Excel 文件并写入数据

This article will explore the IronXL library to demonstrate how to open a Microsoft Excel file and write data to it in a C# Console Application.

IronXL - An Excel Library

IronXL is a .NET Excel Library that facilitates the creation, reading, and editing of Excel files in C# applications. It offers exceptional performance and accurate output. The library supports all Excel workbook file formats, including XLS, XLSX, XLSM, CSV, and TSV. Additionally, it allows data to be saved or exported in formats such as JSON, HTML, Binary, Byte Array, DataSet, or DataTable.

With IronXL, developers can work with worksheets and cell ranges seamlessly. It offers the ability to edit formulas and easily recalculate them within a sheet. Sorting data based on range, column, or row is straightforward. The library provides features to modify layouts, such as freezing panes, auto-sizing rows/columns, and adding/removing rows/columns.

IronXL also enables the protection of Excel files with user passwords and permissions for editing. Another notable feature is the ability to add, remove, and extract images from Excel worksheets. The library offers a wide range of Excel functions, supporting various cell data formats. These features make IronXL one of the most user-friendly APIs for working with Excel files.

One of the significant advantages of IronXL is that it does not require Microsoft Excel to be installed on the machine, eliminating the need for Office Interop or any other dependencies. It is compatible with multiple platforms and supports .NET 7, 6, and 5. It is also compatible with .NET Core 2 and 3, as well as .NET Framework 4.5 and later versions for working with Excel spreadsheets.

Create a Console Application

The latest version of Visual Studio IDE is recommended to create the application. Visual Studio is the official IDE for C# development, and it is assumed that you have already installed it. If you haven't installed Visual Studio, you can download it from the official Microsoft Visual Studio website.

Follow these steps to create a new project named "DemoApp".

  1. Open Visual Studio and click on Create a New Project

    How to Open Excel File and Write Data in C#, Figure 1: New Project New Project

  2. Select Console Application and Click Next

    How to Open Excel File and Write Data in C#, Figure 2: New Project Type New Project Type

  3. Enter the name of the Project

    How to Open Excel File and Write Data in C#, Figure 3: New Project Name New Project Name

  4. Select the .NET version. Choose the stable version .NET 6.0.

    How to Open Excel File and Write Data in C#, Figure 4: New Project Additional Info New Project Additional Info

Install IronXL Library

Once the project is created, the IronXL library needs to be installed in the project to use it. Follow these steps to install it.

  1. Open Manage NuGet Packages for Solutions either from Solution Explorer or Tools.

    How to Open Excel File and Write Data in C#, Figure 5: NuGet Package Manager NuGet Package Manager

  2. Browse for IronXL Library and select the current project. Click install.

    How to Open Excel File and Write Data in C#, Figure 6: Search and install the IronXL package in NuGet Package Manager UI Search and install the IronXL package in NuGet Package Manager UI

Add the following namespace at the top of Program.cs file

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

Open an Existing Excel File in C#

IronXL provides the facility to open an existing Excel file, or you can create a new Excel file. This example is going to open an existing file using C# IronXL.

// Supported spreadsheet formats for reading XLSX, XLS, XLSM, XLTX, CSV and TSV
WorkBook workBook = WorkBook.Load("sample.xlsx");
// Supported spreadsheet formats for reading XLSX, XLS, XLSM, XLTX, CSV and TSV
WorkBook workBook = WorkBook.Load("sample.xlsx");
' Supported spreadsheet formats for reading XLSX, XLS, XLSM, XLTX, CSV and TSV
Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")
$vbLabelText   $csharpLabel

Now, let's select its first worksheet. You can select a worksheet by index number or by name. The DefaultWorkSheet property can help to get the first sheet.

// Select worksheet at index 0
WorkSheet workSheet = workBook.WorkSheets[0];

// Select worksheet by name 
WorkSheet ws = workBook.GetWorkSheet("Sheet1"); 

// Get any existing worksheet
WorkSheet firstSheet = workBook.DefaultWorkSheet;
// Select worksheet at index 0
WorkSheet workSheet = workBook.WorkSheets[0];

// Select worksheet by name 
WorkSheet ws = workBook.GetWorkSheet("Sheet1"); 

// Get any existing worksheet
WorkSheet firstSheet = workBook.DefaultWorkSheet;
' Select worksheet at index 0
Dim workSheet As WorkSheet = workBook.WorkSheets(0)

' Select worksheet by name 
Dim ws As WorkSheet = workBook.GetWorkSheet("Sheet1")

' Get any existing worksheet
Dim firstSheet As WorkSheet = workBook.DefaultWorkSheet
$vbLabelText   $csharpLabel

The code above gets the first sheet from the Excel workbook. For creating a new Excel file with data, check this code example page.

Now, let's write data to the Excel file using the IronXL object library.

Write Data to Excel File in C#

Writing data to an Excel file using IronXL is very easy. There are multiple ways to achieve it, but the simplest method is to use the Excel cell reference.

// Access A1 cell and write the value
workSheet["A1"].Value = "Value using cell reference";
// Access A1 cell and write the value
workSheet["A1"].Value = "Value using cell reference";
' Access A1 cell and write the value
workSheet("A1").Value = "Value using cell reference"
$vbLabelText   $csharpLabel

It is also possible to write data to a range of cells. The following code writes data from cell B1 to B5.

// Write the same value to cells from B1 to B5
workSheet["B1:B5"].Value = "Range value";
// Write the same value to cells from B1 to B5
workSheet["B1:B5"].Value = "Range value";
' Write the same value to cells from B1 to B5
workSheet("B1:B5").Value = "Range value"
$vbLabelText   $csharpLabel

We can also fill in the range with a for loop, making it dynamic. The code goes as follows:

// Specify range in which we want to write the values
for (int i = 1; i <= 5; i++)
{
    // Write the Dynamic value in column C
    workSheet["C" + i].Value = "Value: " + i;

    // Write the Dynamic value in column D
    workSheet["D" + i].Value = "Value: " + i;
}
// Specify range in which we want to write the values
for (int i = 1; i <= 5; i++)
{
    // Write the Dynamic value in column C
    workSheet["C" + i].Value = "Value: " + i;

    // Write the Dynamic value in column D
    workSheet["D" + i].Value = "Value: " + i;
}
' Specify range in which we want to write the values
For i As Integer = 1 To 5
	' Write the Dynamic value in column C
	workSheet("C" & i).Value = "Value: " & i

	' Write the Dynamic value in column D
	workSheet("D" & i).Value = "Value: " & i
Next i
$vbLabelText   $csharpLabel

Another way of writing data to an Excel file is by using the Replace method.

// Replace the value in cell D5
workSheet["D5"].Replace("Value: 5", "Replaced Value");
// Replace the value in cell D5
workSheet["D5"].Replace("Value: 5", "Replaced Value");
' Replace the value in cell D5
workSheet("D5").Replace("Value: 5", "Replaced Value")
$vbLabelText   $csharpLabel

Save an Excel File in C#

This section explains how to save the Excel file with newly written content to it.

// Save the updated Excel workbook to a file
workBook.SaveAs("sample.xlsx");
// Save the updated Excel workbook to a file
workBook.SaveAs("sample.xlsx");
' Save the updated Excel workbook to a file
workBook.SaveAs("sample.xlsx")
$vbLabelText   $csharpLabel

The complete code goes as follows:

using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Supported spreadsheet formats for reading XLSX, XLS, XLSM, XLTX, CSV and TSV
        WorkBook workBook = WorkBook.Load("sample.xlsx");

        // Select worksheet at index 0
        WorkSheet workSheet = workBook.WorkSheets[0];

        // Access A1 cell and write the value
        workSheet["A1"].Value = "Value using cell reference";

        // Write the same value to cells from B1 to B5
        workSheet["B1:B5"].Value = "Range value";

        // Specify range in which we want to write the values
        for (int i = 1; i <= 5; i++)
        {
            // Write the Dynamic value in column C
            workSheet["C" + i].Value = "Value: " + i;

            // Write the Dynamic value in column D
            workSheet["D" + i].Value = "Value: " + i;
        }

        // Replace the value in cell D5
        workSheet["D5"].Replace("Value: 5", "Replaced Value");

        // Save the updated Excel workbook to a file
        workBook.SaveAs("sample.xlsx");
        Console.WriteLine("Successfully written to Excel File");
    }
}
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Supported spreadsheet formats for reading XLSX, XLS, XLSM, XLTX, CSV and TSV
        WorkBook workBook = WorkBook.Load("sample.xlsx");

        // Select worksheet at index 0
        WorkSheet workSheet = workBook.WorkSheets[0];

        // Access A1 cell and write the value
        workSheet["A1"].Value = "Value using cell reference";

        // Write the same value to cells from B1 to B5
        workSheet["B1:B5"].Value = "Range value";

        // Specify range in which we want to write the values
        for (int i = 1; i <= 5; i++)
        {
            // Write the Dynamic value in column C
            workSheet["C" + i].Value = "Value: " + i;

            // Write the Dynamic value in column D
            workSheet["D" + i].Value = "Value: " + i;
        }

        // Replace the value in cell D5
        workSheet["D5"].Replace("Value: 5", "Replaced Value");

        // Save the updated Excel workbook to a file
        workBook.SaveAs("sample.xlsx");
        Console.WriteLine("Successfully written to Excel File");
    }
}
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Supported spreadsheet formats for reading XLSX, XLS, XLSM, XLTX, CSV and TSV
		Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")

		' Select worksheet at index 0
		Dim workSheet As WorkSheet = workBook.WorkSheets(0)

		' Access A1 cell and write the value
		workSheet("A1").Value = "Value using cell reference"

		' Write the same value to cells from B1 to B5
		workSheet("B1:B5").Value = "Range value"

		' Specify range in which we want to write the values
		For i As Integer = 1 To 5
			' Write the Dynamic value in column C
			workSheet("C" & i).Value = "Value: " & i

			' Write the Dynamic value in column D
			workSheet("D" & i).Value = "Value: " & i
		Next i

		' Replace the value in cell D5
		workSheet("D5").Replace("Value: 5", "Replaced Value")

		' Save the updated Excel workbook to a file
		workBook.SaveAs("sample.xlsx")
		Console.WriteLine("Successfully written to Excel File")
	End Sub
End Class
$vbLabelText   $csharpLabel

For more detailed information on how to read Excel file data in C#, have a look at this example.

Output

The output of the file is:

How to Open Excel File and Write Data in C#, Figure 7: The output Excel file The output Excel file

Summary

This article demonstrated how to write data to Excel files in C# using IronXL. IronXL provides the facility to work with existing Excel files without any hassle. It also allows you to create new Excel files and write data to it with easy syntax. IronXL can also be used to read Excel files without the Microsoft Excel application installed. To read data from Excel files you can see this code example page.

IronXL is free for development and can be licensed for commercial use. You can also try the IronXL free trial for commercial use.

常见问题解答

如何在C#中打开Excel文件而不使用Interop?

您可以通过使用IronXL库在C#中打开Excel文件而不使用Interop。IronXL允许您高效地处理Excel文件,而无需Microsoft Excel安装,提升性能和兼容性。

如何在C#中使用Excel文件的特定单元格写入数据?

使用IronXL,您可以通过访问工作簿,选择工作表,然后使用单元格引用为所需单元格分配值,在Excel文件中写入数据。

使用IronXL在Excel文件操作中有什么优于Office Interop的优势?

IronXL相较Office Interop有多个优势,包括不依赖于Microsoft Excel安装,改进的性能,跨平台兼容性,以及支持多种Excel文件格式如XLS、XLSX和CSV。

我可以使用这个库编辑Excel文件中的公式吗?

是的,IronXL允许您编辑Excel文件中的公式。您可以使用简单的语法操作现有公式或插入新公式,库会高效地处理这些操作。

IronXL 如何支持不同的 Excel 文件格式?

IronXL支持多种Excel文件格式,如XLS、XLSX、XLSM、CSV和TSV,使您能够在C#应用程序中无缝创建、读取和编辑这些文件。

可以使用IronXL保护Excel文件吗?

是的,IronXL提供了通过设置用户密码和权限来保护Excel文件的功能,以确保数据安全和受控访问。

如何将IronXL库集成到我的C#项目中?

要将IronXL集成到您的C#项目中,您可以在Visual Studio中使用NuGet包管理器。搜索IronXL,并将其添加到您的项目中以开始使用其功能。

IronXL 支持哪些平台?

IronXL支持多种平台,包括.NET 5、6 和 7 版,以及.NET Core 和框架,使之成为各种开发环境的多功能选择。

我可以免费使用IronXL吗?

IronXL可在开发中免费使用。然而,商业用途需要许可证。提供免费试用以在商业环境中测试库的功能。

如何使用IronXL将Excel数据导出为JSON?

IronXL允许您通过将工作表或特定数据范围转换为JSON字符串将Excel数据导出为JSON格式,然后可以在需要JSON数据的应用程序中使用。

Curtis Chau
技术作家

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

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