使用IRONXL

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

本文將探討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。

    如何打開 Excel 檔案並在 C# 中寫入資料,圖 4:新專案附加資訊

    新專案附加資訊

安裝 IronXL 程式庫

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

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

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

    NuGet 套件管理器

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

    如何在 C# 中開啟 Excel 檔案並寫入資料,圖 6:在 NuGet 套件管理器 UI 中搜尋並安裝 IronXL 套件

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

    Program.cs 檔案的頂部添加以下命名空間

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

在 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")
$vbLabelText   $csharpLabel

現在,讓我們選擇其第一個工作表。 您可以透過索引號或名稱選擇工作表。 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
$vbLabelText   $csharpLabel

上面的代碼從 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"
$vbLabelText   $csharpLabel

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

workSheet ["B1:B5"].Value = "Range value";
workSheet ["B1:B5"].Value = "Range value";
workSheet ("B1:B5").Value = "Range value"
$vbLabelText   $csharpLabel

我們也可以使用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
$vbLabelText   $csharpLabel

另一種將資料寫入 Excel 檔案的方法是使用Replace方法。

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

在 C# 中儲存 Excel 文件

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

workBook.SaveAs("sample.xlsx");
workBook.SaveAs("sample.xlsx");
workBook.SaveAs("sample.xlsx")
$vbLabelText   $csharpLabel

代碼如下:

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
$vbLabelText   $csharpLabel

如需了解更多有關如何在 C# 中讀取 Excel 文件數據的詳細信息,請參閱此範例

輸出

檔案的輸出為:

如何在 C# 中開啟 Excel 檔案並寫入資料,圖 7:輸出 Excel 檔案

輸出的 Excel 檔案

摘要

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

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

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