使用IRONXL

如何在 C# 中打開 Excel 文件並寫入數據

已更新 2024年3月31日
分享:

本文將探討IronXL庫,以展示如何在C#控制台應用程序中打開Microsoft Excel文件並向其寫入數據。

IronXL - Excel庫

IronXL是一個 .NET Excel 庫,用於在 C# 應用程式中創建、讀取和編輯 Excel 檔案。 它提供卓越的性能和精確的輸出。 該庫支持所有 Excel 活頁簿文件格式,包括 XLS、XLSX、XLSM、CSV 和 TSV。此外,它允許以 JSON、HTML、二進制、字節數組等格式保存或導出數據。資料集(DataSet)、或資料表(DataTable).

使用 IronXL,開發人員可以無縫地處理工作表和儲存格範圍。 它提供了編輯公式並在工作表中輕鬆重新計算的功能。 排序資料基於範圍、列或行是簡單的。 該庫提供修改佈局的功能,例如凍結窗格, 自動調整行/列,和添加/刪除行/列.

IronXL也啟用保護具有用戶密碼和編輯權限的 Excel 文件。 另一個值得注意的功能是能夠從 Excel 工作表中添加、刪除和提取圖像。 該程式庫提供廣泛的 Excel 功能,支援各種儲存格數據格式. 這些功能使 IronXL 成為處理 Excel 文件時最易於使用的 API 之一。

IronXL 的一個顯著優勢是,不需要在機器上安裝 Microsoft Excel,不需要使用 Office Interop 或任何其他相依性。 它兼容多平臺,支持 .NET 7、6 和 5。還兼容 .NET Core 2 和 3,以及 .NET Framework 4.5 及更高版本,用於處理 Excel 試算表。

建立主控台應用程式

建議使用最新版本的 Visual Studio IDE 來建立應用程式。 Visual Studio 是官方的 C# 開發 IDE,假設您已經安裝了它。 如果您尚未安裝 Visual Studio,您可以從官方下載Microsoft Visual Studio 網站.

請按照以下步驟創建一個名為「DemoApp」的新專案。

  1. 開啟 Visual Studio 並點擊「建立新專案」

    如何在 C# 中打開 Excel 文件並寫入數據,圖 1:新項目

    新專案

  2. 選擇控制台應用程式並點擊下一步

    如何在 C# 中開啟 Excel 文件並寫入數據,圖 2:新專案類型

    新專案類型

  3. 輸入專案名稱

    如何在C#中打開Excel文件並寫入數據,圖3:新專案名稱

    新專案名稱

  4. 選擇 .NET 版本。 選擇穩定版本 .NET 6.0。

    如何在 C# 中打開 Excel 文件並寫入數據,圖 4:新專案附加資訊

    新專案附加資訊

安裝 IronXL 程式庫

一旦專案建立,就需要在專案中安裝IronXL庫以使用它。 按照以下步驟進行安裝。

  1. 從解決方案總管或工具打開管理 NuGet 套件。

    如何在 C# 中打開 Excel 文件並寫入數據,圖 5:NuGet 套件管理器

    NuGet 套件管理器

  2. 瀏覽 IronXL 庫並選擇當前專案。 點擊安裝。

    如何在 C# 中開啟 Excel 文件並寫入數據,圖 6:在 NuGet 套件管理器 UI 中搜索並安裝 IronXL 套件

    在 NuGet 包管理器 UI 中搜尋並安裝 IronXL 套件

    Program.cs 文件的顶部添加以下命名空间

using IronXL;
using IronXL;
Imports IronXL
VB   C#

在 C# 中開啟現有的 Excel 檔案

IronXL 提供開啟現有 Excel 文件的功能,或您可以創建新的 Excel 文件。本範例將使用 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")
VB   C#

現在,讓我們選擇其第一個工作表。 您可以透過索引號或名稱選擇工作表。 DefaultWorkSheet 屬性可以用來取得第一個工作表。

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

// Select worksheet by name 
WorkSheet ws = wb.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 = wb.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 = wb.GetWorkSheet("Sheet1")

' Get any existing worksheet
Dim firstSheet As WorkSheet = workBook.DefaultWorkSheet
VB   C#

上面的代碼從 Excel 活頁簿中獲取第一個工作表。 要創建一個包含數據的新 Excel 文件,請查看此內容程式碼範例頁面.

現在,讓我們使用IronXL物件庫將數據寫入Excel文件。

在 C# 中將資料寫入 Excel 文件

使用 IronXL 寫入資料到 Excel 文件非常簡單。 有多種方式可以將其歸檔,但最簡單的方法是使用 Excel 儲存格參照。

// 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"
VB   C#

也可以將數據寫入一個範圍的單元格。 以下程式碼寫入資料從儲存格 B1 到 B5。

workSheet ["B1:B5"].Value = "Range value";
workSheet ["B1:B5"].Value = "Range value";
workSheet ("B1:B5").Value = "Range value"
VB   C#

我們也可以使用 for 迴圈填充範圍,使其動態化。 代碼如下:

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

    //write the Dynamic value in another row
    ws ["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 one row
    workSheet ["C" + i].Value = "Value: " + i;

    //write the Dynamic value in another row
    ws ["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 one row
	workSheet ("C" & i).Value = "Value: " & i

	'write the Dynamic value in another row
	ws ("D" & i).Value = "Value: " & i
Next i
VB   C#

另一種將數據寫入 Excel 文件的方法是使用取代方法。

workSheet ["D5"].Replace("Value: 5", "Replaced Value");
workSheet ["D5"].Replace("Value: 5", "Replaced Value");
workSheet ("D5").Replace("Value: 5", "Replaced Value")
VB   C#

在 C# 中儲存 Excel 文件

此部分說明如何將新增的內容儲存至 Excel 文件中。

workBook.SaveAs("sample.xlsx");
workBook.SaveAs("sample.xlsx");
workBook.SaveAs("sample.xlsx")
VB   C#

代碼如下:

using System;
using IronXL;

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";

    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 one row
        workSheet ["C" + i].Value = "Value: " + i;

        //write the Dynamic value in another row
        workSheet ["D" + i].Value = "Value: " + i;
    }

    workSheet ["D5"].Replace("Value: 5", "Replaced Value");

    workBook.SaveAs("sample.xlsx");
    Console.WriteLine("successfully written in Excel File");
}
using System;
using IronXL;

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";

    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 one row
        workSheet ["C" + i].Value = "Value: " + i;

        //write the Dynamic value in another row
        workSheet ["D" + i].Value = "Value: " + i;
    }

    workSheet ["D5"].Replace("Value: 5", "Replaced Value");

    workBook.SaveAs("sample.xlsx");
    Console.WriteLine("successfully written in Excel File");
}
Imports System
Imports IronXL

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"

	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 one row
		workSheet ("C" & i).Value = "Value: " & i

		'write the Dynamic value in another row
		workSheet ("D" & i).Value = "Value: " & i
	Next i

	workSheet ("D5").Replace("Value: 5", "Replaced Value")

	workBook.SaveAs("sample.xlsx")
	Console.WriteLine("successfully written in Excel File")
End Sub
VB   C#

有關如何在C#中讀取Excel文件數據的更多詳細信息,請查看這個範例.

輸出

檔案的輸出為:

如何在 C# 中打開 Excel 文件並寫入數據,圖 7:輸出 Excel 文件

輸出 Excel 文件

摘要

本文演示了如何使用IronXL在C#中將數據寫入Excel文件。 IronXL 提供了輕鬆處理現有 Excel 文件的功能。 它還允許您使用簡單的語法創建新的 Excel 文件並向其寫入數據。 IronXL 也可以用來讀取 Excel 文件,而不需要安裝 Microsoft Excel 應用程式。 若要從 Excel 文件讀取資料,您可以查看這個程式碼範例頁面.

IronXL 是免費供開發使用的,並可以獲得商業用途的許可。 您還可以試用 IronXL 免費版試用商業用途。

里根普恩

里根普恩

軟體工程師

 LinkedIn

Regan 畢業於雷丁大學,擁有電子工程學士學位。在加入 Iron Software 之前,他的工作角色讓他專注於單一任務;而他在 Iron Software 工作中最喜歡的是他所能承擔的工作範圍,無論是增加銷售價值、技術支持、產品開發或市場營銷。他喜歡了解開發人員如何使用 Iron Software 庫,並利用這些知識不斷改進文檔和開發產品。
< 上一頁
如何使用 C# 禁用 Excel 中的受保护视图
下一個 >
如何在C#中將海量數據從DataTable匯出到Excel