如何在 C# 中使用 Excel Interop 的另一種方法

C# Excel Interop Workaround

This article was translated from English: Does it need improvement?
Translated
View the article in English

許多專案使用 Excel 來進行清晰的溝通,但如果您正在使用 Microsoft.Office.Interop.Excel,那麼您可能已經面對過許多複雜的代碼行。 在本教程中,我們將使用 IronXL 作為 C# Excel Interop 的繞過方法,因此您不需要使用 Interop 即可完成項目。 您可以使用 Excel 文件數據,創建 Excel 文件,編輯並使用 C# 編程進行操作。

class="learnn-how-section">
class="row">
class="col-sm-6">

C# Excel 無 Interop

  • 下載 Excel 無 Interop 庫
  • C# 中訪問 Excel 文件
  • 程式化創建新 Excel 文件並插入數據
  • 修改現有文件,更新並替換單元格值,刪除行等
class="col-sm-6">
class="download-card"> How To Work related to C# Excel Interop Workaround

如何用其他方式使用 Excel Interop

  1. 安裝一個 Excel 庫來處理 Excel 文件。
  2. 打開 Workbook 並添加當前的 Excel 文件。
  3. 設置默認的 Worksheet。
  4. 從 Excel Workbook 中讀取值。
  5. 處理並顯示值。

class="tutorial-segment-title">步驟 1

1. 下載 IronXL 庫

Download IronXL Library or 使用 NuGet 安裝來訪問免費庫,然後按照步驟在本教程中學習如何不使用 Interop 操作 Excel 文件。如果您打算將項目上線,還提供許可證。

Install-Package IronXL.Excel

class="tutorial-segment-title">教程指南

2. 訪問 Excel 文件數據

要開發業務應用程序,我們需要方便且完美地訪問 Excel 文件中的數據,並根據各種需求程式化操作數據。 使用 IronXL,請使用 WorkBook.Load() 函數,它允許訪問特定的 Excel 文件。

訪問 WorkBook 後,您可以使用 WorkBook.GetWorkSheet() 函數選擇特定的 WorkSheet。 現在所有的 Excel 文件數據都可以使用了。 請看下面的示例,了解我們如何使用這些函數在 C# 項目中獲取 Excel 文件數據。

// Import the IronXL library to access its functionality
using IronXL;

static void Main(string[] args)
{
    // Access Excel file
    WorkBook wb = WorkBook.Load("sample.xlsx");
    // Access WorkSheet of Excel file
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Get a specific cell value, convert it to a string, and print it
    string a = ws["A5"].Value.ToString();
    Console.WriteLine("Getting Single Value:\n\n   Value of Cell A5: {0}", a);

    Console.WriteLine("\nGetting Many Cells Value using Loop:\n");
    // Get multiple cell values using range function and iterate through them
    foreach (var cell in ws["B2:B10"])
    {
        Console.WriteLine("   Value is: {0}", cell.Text);
    }

    Console.ReadKey(); // Pause the console to view output
}
// Import the IronXL library to access its functionality
using IronXL;

static void Main(string[] args)
{
    // Access Excel file
    WorkBook wb = WorkBook.Load("sample.xlsx");
    // Access WorkSheet of Excel file
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Get a specific cell value, convert it to a string, and print it
    string a = ws["A5"].Value.ToString();
    Console.WriteLine("Getting Single Value:\n\n   Value of Cell A5: {0}", a);

    Console.WriteLine("\nGetting Many Cells Value using Loop:\n");
    // Get multiple cell values using range function and iterate through them
    foreach (var cell in ws["B2:B10"])
    {
        Console.WriteLine("   Value is: {0}", cell.Text);
    }

    Console.ReadKey(); // Pause the console to view output
}
' Import the IronXL library to access its functionality
Imports Microsoft.VisualBasic
Imports IronXL

Shared Sub Main(ByVal args() As String)
	' Access Excel file
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	' Access WorkSheet of Excel file
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

	' Get a specific cell value, convert it to a string, and print it
	Dim a As String = ws("A5").Value.ToString()
	Console.WriteLine("Getting Single Value:" & vbLf & vbLf & "   Value of Cell A5: {0}", a)

	Console.WriteLine(vbLf & "Getting Many Cells Value using Loop:" & vbLf)
	' Get multiple cell values using range function and iterate through them
	For Each cell In ws("B2:B10")
		Console.WriteLine("   Value is: {0}", cell.Text)
	Next cell

	Console.ReadKey() ' Pause the console to view output
End Sub
$vbLabelText   $csharpLabel

此代碼將產生以下結果:

class="center-image-wrapper"> 1output related to 2. 訪問 Excel 文件數據

Excel 文件如下所示:

class="center-image-wrapper"> 1excel related to 2. 訪問 Excel 文件數據

我們可以看到我們的 Excel 文件 sample.xlsxA5 單元格中有 small business。 從 B2B10 的其他值都相同,並且顯示在輸出中。

DataSet 和 DataTables

我們也可以將 Excel 文件作為數據集和數據表來使用。

// Access WorkBook and WorkSheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");

// Convert workbook to DataSet
DataSet ds = wb.ToDataSet();

// Convert worksheet to DataTable
DataTable dt = ws.ToDataTable(true);
// Access WorkBook and WorkSheet
WorkBook wb = WorkBook.Load("sample.xlsx");
WorkSheet ws = wb.GetWorkSheet("Sheet1");

// Convert workbook to DataSet
DataSet ds = wb.ToDataSet();

// Convert worksheet to DataTable
DataTable dt = ws.ToDataTable(true);
' Access WorkBook and WorkSheet
Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

' Convert workbook to DataSet
Dim ds As DataSet = wb.ToDataSet()

' Convert worksheet to DataTable
Dim dt As DataTable = ws.ToDataTable(True)
$vbLabelText   $csharpLabel

您可以閱讀更多關於如何使用 Excel DataSet 和 DataTables,其中提供了更多代碼示例和過程解釋。

現在,我們將看到另一個方面,即在我們的 C# 項目中創建一個新的 Excel 文件。


3. 創建新的 Excel 文件

我們可以輕鬆地創建一個新的 Excel 工作表,並在我們的 C# 項目中以程式化方式插入數據。 為了實現這一點,IronXL 提供了 WorkBook.Create() 函數,該函數創建一個新的 Excel 文件。

然後我們可以使用 WorkBook.CreateWorkSheet() 函數創建多個 WorkSheets。

之後,我們還可以插入數據,如下面的示例所示:

// Import the IronXL library
using IronXL;

static void Main(string[] args)
{
    // Create a new WorkBook
    WorkBook wb = WorkBook.Create();

    // Create a new WorkSheet in the workbook
    WorkSheet ws = wb.CreateWorkSheet("sheet1");

    // Insert data into cells
    ws["A1"].Value = "New Value A1";
    ws["B2"].Value = "New Value B2";

    // Save the newly created Excel file
    wb.SaveAs("NewExcelFile.xlsx");
}
// Import the IronXL library
using IronXL;

static void Main(string[] args)
{
    // Create a new WorkBook
    WorkBook wb = WorkBook.Create();

    // Create a new WorkSheet in the workbook
    WorkSheet ws = wb.CreateWorkSheet("sheet1");

    // Insert data into cells
    ws["A1"].Value = "New Value A1";
    ws["B2"].Value = "New Value B2";

    // Save the newly created Excel file
    wb.SaveAs("NewExcelFile.xlsx");
}
' Import the IronXL library
Imports IronXL

Shared Sub Main(ByVal args() As String)
	' Create a new WorkBook
	Dim wb As WorkBook = WorkBook.Create()

	' Create a new WorkSheet in the workbook
	Dim ws As WorkSheet = wb.CreateWorkSheet("sheet1")

	' Insert data into cells
	ws("A1").Value = "New Value A1"
	ws("B2").Value = "New Value B2"

	' Save the newly created Excel file
	wb.SaveAs("NewExcelFile.xlsx")
End Sub
$vbLabelText   $csharpLabel

上面的代碼將創建一個名為 NewExcelFile.xlsx 的新 Excel 文件,並在單元格地址 A1B2 插入新的數據值 New Value A1New Value B2。 通過此設置,您可以隨著需要插入數據。

注意:如果您正在創建新的 Excel 文件或修改現有文件,請不要忘記如上面的示例中所示地保存文件。

深入了解如何 使用 C# 創建新的 Excel SpreadSheets,並將代碼應用到您的項目中。


4. 修改現有的 Excel 文件

我們可以修改現有的 Excel 文件,並以程式化方式插入更新的數據。 在 Excel 文件修改中,我們將看到以下方面:

  • 更新單元格值
  • 用新值替換舊值
  • 刪除行或列

讓我們看看如何在我們的 C# 專案中實施上述主題。

更新單元格值

更新現有 Excel 工作表的單元格值非常簡單。 只需在項目中訪問 Excel 文件並指定其 WorkSheet,然後按照以下示例更新其數據:

// Import the IronXL library
using IronXL;

static void Main(string[] args)
{
    // Access the WorkBook and WorkSheet
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Update A3 cell value
    ws["A3"].Value = "New Value of A3";

    // Save the updated Excel file
    wb.SaveAs("sample.xlsx");
}
// Import the IronXL library
using IronXL;

static void Main(string[] args)
{
    // Access the WorkBook and WorkSheet
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Update A3 cell value
    ws["A3"].Value = "New Value of A3";

    // Save the updated Excel file
    wb.SaveAs("sample.xlsx");
}
' Import the IronXL library
Imports IronXL

Shared Sub Main(ByVal args() As String)
	' Access the WorkBook and WorkSheet
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

	' Update A3 cell value
	ws("A3").Value = "New Value of A3"

	' Save the updated Excel file
	wb.SaveAs("sample.xlsx")
End Sub
$vbLabelText   $csharpLabel

上面的代碼將更新單元格 A3 的值為 New Value of A3

我們還可以使用範圍功能以靜態值更新多個單元格:

ws["A3:C3"].Value = "New Value";
ws["A3:C3"].Value = "New Value";
ws("A3:C3").Value = "New Value"
$vbLabelText   $csharpLabel

這將在 Excel 文件中將第 3 行從 A3C3 的單元格更新為 New Value

通過這些示例了解更多關於如何在 C# 中使用 範圍功能

替換單元格值

IronXL 的一個優勢是能夠輕鬆地將現有 Excel 文件中的 老值 替換為 新值,涵蓋以下所有方面:

  • 替換整個 WorkSheet 的值:
ws.Replace("old value", "new value");
ws.Replace("old value", "new value");
ws.Replace("old value", "new value")
$vbLabelText   $csharpLabel
  • 替換特定行的值:
ws.Rows[RowIndex].Replace("old value", "new value");
ws.Rows[RowIndex].Replace("old value", "new value");
ws.Rows(RowIndex).Replace("old value", "new value")
$vbLabelText   $csharpLabel
  • 替換特定列的值:
ws.Columns[ColumnIndex].Replace("old value", "new Value");
ws.Columns[ColumnIndex].Replace("old value", "new Value");
ws.Columns(ColumnIndex).Replace("old value", "new Value")
$vbLabelText   $csharpLabel
  • 替換特定範圍中的值:
ws["From:To"].Replace("old value", "new value");
ws["From:To"].Replace("old value", "new value");
ws("From:To").Replace("old value", "new value")
$vbLabelText   $csharpLabel

讓我們查看一個示例,清楚地了解如何在我們的 C# 專案中使用上述功能替換值。 在此示例中,我們將使用替換功能替換特定範圍內的值。

// Import the IronXL library
using IronXL;

static void Main(string[] args)
{
    // Access the WorkBook and WorkSheet
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Specify a range from B5 to G5 and replace "Normal" value with "Good"
    ws["B5:G5"].Replace("Normal", "Good");

    // Save the updated Excel file
    wb.SaveAs("sample.xlsx");
}
// Import the IronXL library
using IronXL;

static void Main(string[] args)
{
    // Access the WorkBook and WorkSheet
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Specify a range from B5 to G5 and replace "Normal" value with "Good"
    ws["B5:G5"].Replace("Normal", "Good");

    // Save the updated Excel file
    wb.SaveAs("sample.xlsx");
}
' Import the IronXL library
Imports IronXL

Shared Sub Main(ByVal args() As String)
	' Access the WorkBook and WorkSheet
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

	' Specify a range from B5 to G5 and replace "Normal" value with "Good"
	ws("B5:G5").Replace("Normal", "Good")

	' Save the updated Excel file
	wb.SaveAs("sample.xlsx")
End Sub
$vbLabelText   $csharpLabel

上面的代碼將把值 NormalB5G5 替換為 Good,而 WorkSheet 的其餘部分保持不變。 了解更多關於如何使用 IronXL 函數 編輯 Excel 範圍中的單元格值

移除 Excel 文件的行

在應用程序開發中,有時候我們需要程式化地移除現有 Excel 文件的整行。 這項任務我們使用 IronXL 的 Remove() 函數。 以下是一個示例:

// Import the IronXL library
using IronXL;

static void Main(string[] args)
{
    // Access the WorkBook and WorkSheet
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Remove the row number 2
    ws.Rows[2].Remove();

    // Save the updated Excel file
    wb.SaveAs("sample.xlsx");
}
// Import the IronXL library
using IronXL;

static void Main(string[] args)
{
    // Access the WorkBook and WorkSheet
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");

    // Remove the row number 2
    ws.Rows[2].Remove();

    // Save the updated Excel file
    wb.SaveAs("sample.xlsx");
}
' Import the IronXL library
Imports IronXL

Shared Sub Main(ByVal args() As String)
	' Access the WorkBook and WorkSheet
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")

	' Remove the row number 2
	ws.Rows(2).Remove()

	' Save the updated Excel file
	wb.SaveAs("sample.xlsx")
End Sub
$vbLabelText   $csharpLabel

上面的代碼將移除 sample.xlsx 的第 2 行。


class="tutorial-segment-title">教程快速訪問

class="tutorial-section">
class="row">
class="col-sm-8">

IronXL 參考

閱讀 IronXL 的 API 參考以獲取有關所有功能、特性、類別和命名空間的更多信息。

IronXL 參考
class="col-sm-4">
class="tutorial-image"> Documentation related to class=教程快速訪問" class="img-responsive add-shadow img-responsive img-popup" src="/img/svgs/documentation.svg" loading="lazy">

常見問題解答

如何在不使用 Interop 的情況下用 C# 讀取 Excel 檔案?

您可以使用 IronXL 在 C# 中讀取 Excel 文件,而無需 Interop。使用WorkBook.Load()函數載入文件,並使用WorkBook.GetWorkSheet()存取工作表。

如何使用 C# 程式設計方式建立新的 Excel 檔案?

使用 IronXL,您可以使用WorkBook.Create()方法建立一個新的 Excel 文件,然後使用WorkSheet.CreateWorkSheet()在其中新增資料。

是否可以在不使用 Interop 的情況下,用 C# 修改 Excel 檔案?

是的,IronXL 提供了無需 Interop 即可修改 Excel 檔案的功能,可直接更新儲存格值、取代舊值以及刪除行或列。

如何使用 IronXL 更新 Excel 表格中特定儲存格的值?

若要更新儲存格值,請使用WorkBook.GetWorkSheet()載入工作表,為儲存格賦新值,然後儲存變更。

我可以使用 IronXL 替換一系列儲存格中的值嗎?

IronXL 可讓您使用Replace()函數來取代工作表或特定範圍物件中的值。

與 Microsoft.Office.Interop.Excel 相比,使用 IronXL 有哪些優點?

IronXL 透過提供易於使用的 API 簡化了 Excel 檔案操作,減少了對複雜互通程式碼的需求,並提供了更好的效能和可靠性。

如何使用 IronXL 從 Excel 檔案中刪除一行?

若要在 IronXL 中刪除行,請在工作表的指定行物件上使用Remove()函數。

IronXL 是否支援將 Excel 檔案轉換為 DataSet 和 DataTable?

是的,IronXL 支援將工作簿轉換為資料集,將工作表轉換為資料表,從而實現更靈活的資料操作。

如何在 C# 專案中安裝 IronXL?

您可以透過從 Iron Software 網站下載或使用 NuGet 套件管理器透過以下命令將 IronXL 安裝到您的 C# 專案: Install-Package IronXL.Excel

IronXL 是否適用於處理大型 Excel 檔案?

IronXL 經過最佳化,能夠高效處理大型 Excel 文件,與傳統的互通方法相比,可提供更快的處理速度和更小的記憶體佔用。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 1,686,155 | 版本: 2025.11 剛剛發布