C# 编辑 Excel 文件

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

開發人員在使用 C# 修改和編輯 Excel 文件時需要小心,因為一個小錯誤就可能改變整個文件。能夠依賴簡單且高效的代碼行有助於減少錯誤風險,並使我們能夠以程序方式更輕鬆地編輯或刪除 Excel 文件。今天我們將介紹使用經過測試的函數來正確且快速地編輯 C# 中的 Excel 文件的必要步驟。


第一步

1. 使用 IronXL 庫編輯 C# Excel 文件

在本教程中,我們將使用 IronXL 定義的功能,它是一個 C# Excel 庫。要使用這些功能,您需要首先下載並將其安裝到項目中 (開發免費使用)你可以 either 下載 IronXL.zip 或閱讀更多並通過以下方式安裝 NuGet 套件頁面一旦安裝完成,就讓我們開始吧!


Install-Package IronXL.Excel

如何操作教程

2. 編輯特定的儲存格值

首先,我們將看看如何編輯 Excel 試算表中特定的儲存格值。

為此,我們需要導入要修改的 Excel 試算表,然後訪問其工作表。接下來,我們可以按照下圖進行修改。

/**
Import and Edit SpreadSheet
anchor-edit-specific-cell-values
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");//import Excel SpreadSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");//access specific workshet
    ws.Rows [3].Columns [1].Value = "New Value";//access specific cell and modify its value
    wb.SaveAs("sample.xlsx");//save changes
}
/**
Import and Edit SpreadSheet
anchor-edit-specific-cell-values
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");//import Excel SpreadSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");//access specific workshet
    ws.Rows [3].Columns [1].Value = "New Value";//access specific cell and modify its value
    wb.SaveAs("sample.xlsx");//save changes
}
'''
'''Import and Edit SpreadSheet
'''anchor-edit-specific-cell-values
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx") 'import Excel SpreadSheet
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1") 'access specific workshet
	ws.Rows (3).Columns (1).Value = "New Value" 'access specific cell and modify its value
	wb.SaveAs("sample.xlsx") 'save changes
End Sub
VB   C#

Here are before and after screenshots of Excel SpreadSheet sample.xlsx:

Before After

:---: :-----:

before after

We can see how simple it is to modify the Excel SpreadSheet value.

If needed, there is also an alternative way to edit the specific cell value by cell address:

 ws ["B4"].Value = "New Value"; //alternative way to access specific cell and apply changes
 ws ["B4"].Value = "New Value"; //alternative way to access specific cell and apply changes
ws ("B4").Value = "New Value" 'alternative way to access specific cell and apply changes
VB   C#

3. 編輯整行數值

編輯 Excel 試算表整行數值為靜態值非常簡單。

/**
Edit Full Row Values
anchor-edit-full-row-values
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    ws.Rows [3].Value = "New Value";        
    wb.SaveAs("sample.xlsx");
}
/**
Edit Full Row Values
anchor-edit-full-row-values
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    ws.Rows [3].Value = "New Value";        
    wb.SaveAs("sample.xlsx");
}
'''
'''Edit Full Row Values
'''anchor-edit-full-row-values
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	ws.Rows (3).Value = "New Value"
	wb.SaveAs("sample.xlsx")
End Sub
VB   C#

請參閱以下 sample.xlsx 的截圖:

前 後

:---: :-----:

之前 之後

為此,我們還可以透過使用 range 函數來編輯特定行範圍的值:

ws ["A3:E3"].Value = "New Value";
ws ["A3:E3"].Value = "New Value";
ws ("A3:E3").Value = "New Value"
VB   C#

4. 編輯整列數值

和上述方法一樣,我們可以輕鬆地用單一數值編輯 Excel 試算表的整列數值。

/**
Edit Full Column Values
anchor-edit-full-column-values
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    ws.Columns [1].Value = "New Value";
    wb.SaveAs("sample.xlsx");
}
/**
Edit Full Column Values
anchor-edit-full-column-values
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    ws.Columns [1].Value = "New Value";
    wb.SaveAs("sample.xlsx");
}
'''
'''Edit Full Column Values
'''anchor-edit-full-column-values
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	ws.Columns (1).Value = "New Value"
	wb.SaveAs("sample.xlsx")
End Sub
VB   C#

這將產生我們的 sample.xlsx 試算表,如下所示:

之前 之後

:---: :-----:

之前 之後


5. 使用動態值編輯整行

使用IronXL,我們也可以用動態值編輯特定行。這表示我們可以通過為每個儲存格分配動態值來編輯整行。讓我們看看這個例子:

/**
Edit Row Dynamic Values
anchor-edit-full-row-with-dynamic-values
**/
using IronXL;
static void Main(string [] args)
{

    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    for (int i = 0; i < ws.Columns.Count(); i++)
    {
        ws.Rows [3].Columns [i].Value = "New Value "+i.ToString();
    }        
    wb.SaveAs("sample.xlsx");
}
/**
Edit Row Dynamic Values
anchor-edit-full-row-with-dynamic-values
**/
using IronXL;
static void Main(string [] args)
{

    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    for (int i = 0; i < ws.Columns.Count(); i++)
    {
        ws.Rows [3].Columns [i].Value = "New Value "+i.ToString();
    }        
    wb.SaveAs("sample.xlsx");
}
'''
'''Edit Row Dynamic Values
'''anchor-edit-full-row-with-dynamic-values
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)

	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	For i As Integer = 0 To ws.Columns.Count() - 1
		ws.Rows (3).Columns (i).Value = "New Value " & i.ToString()
	Next i
	wb.SaveAs("sample.xlsx")
End Sub
VB   C#

在下表中,我們看到來自此輸出中 Excel 試算表 sample.xlsx 的屏幕截圖:

之前 之後

:---: :---:

之前 之後


6. 使用動態值編輯整列

使用動態值編輯特定的列也很簡單。

/**
Edit Column Dynamic Values
anchor-edit-full-column-with-dynamic-values
**/
using IronXL;
static void Main(string [] args)
{

    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    for (int i = 0; i < ws.Rows.Count(); i++)
    {
        if (i == 0)//it is for if our first column is used as a header
            continue;
        ws.Rows [i].Columns [1].Value = "New Value " + i.ToString();
    }
    wb.SaveAs("sample.xlsx");
}
/**
Edit Column Dynamic Values
anchor-edit-full-column-with-dynamic-values
**/
using IronXL;
static void Main(string [] args)
{

    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    for (int i = 0; i < ws.Rows.Count(); i++)
    {
        if (i == 0)//it is for if our first column is used as a header
            continue;
        ws.Rows [i].Columns [1].Value = "New Value " + i.ToString();
    }
    wb.SaveAs("sample.xlsx");
}
'''
'''Edit Column Dynamic Values
'''anchor-edit-full-column-with-dynamic-values
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)

	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	For i As Integer = 0 To ws.Rows.Count() - 1
		If i = 0 Then 'it is for if our first column is used as a header
			Continue For
		End If
		ws.Rows (i).Columns (1).Value = "New Value " & i.ToString()
	Next i
	wb.SaveAs("sample.xlsx")
End Sub
VB   C#

下表顯示了 sample.xlsx 的結果:

BeforeAfter

之前 之後


7. 替換電子表格的數值

如果我們想用更新後的數值替換 Excel 電子表格中的任何類型數值,可以使用名為 Replace 的函數。使用此函數,我們可以在任何需要的情況下替換 Excel 電子表格中的數據。

7.1. 替換整個工作表的特定值

要將整個 Excel 工作表的特定值替換為更新的值,我們只需訪問工作表 ws (與上述示例相同) 並像這樣應用Replace函數。

/**
Replace Cell Values
anchor-replace-specific-value-of-complete-worksheet
**/
ws.Replace("old value", "new value");
/**
Replace Cell Values
anchor-replace-specific-value-of-complete-worksheet
**/
ws.Replace("old value", "new value");
'''
'''Replace Cell Values
'''anchor-replace-specific-value-of-complete-worksheet
'''*
ws.Replace("old value", "new value")
VB   C#

此功能將在整個 Excel 工作表中使用 new value 替換 old value

更改後,請不要忘記保存文件,如上述範例所示。

7.2. 替換特定行的值

如果您只想更改特定行,而不是整個工作表的其餘部分,請使用以下代碼。

ws.Rows [2].Replace("old value", "new value");
ws.Rows [2].Replace("old value", "new value");
ws.Rows (2).Replace("old value", "new value")
VB   C#

上述程式碼將僅在第 2 行將 old value 替換為 new value。工作表的其餘部分保持不變。

7.3. 替換行範圍內的值

我們也可以依照下列方式替換一個特定範圍內的值:

ws ["From Cell Address : To Cell Address"].Replace("old value", "new value");
ws ["From Cell Address : To Cell Address"].Replace("old value", "new value");
ws ("From Cell Address : To Cell Address").Replace("old value", "new value")
VB   C#

假設我們想在第 4 行的範圍從 B4E4 中用新值替換舊值,那麼我們會這樣寫:

ws ["B4:E4"].Replace("old value", "new value");
ws ["B4:E4"].Replace("old value", "new value");
ws ("B4:E4").Replace("old value", "new value")
VB   C#

7.4. 更換特定欄位的值

我們也可以更換特定欄位的值,其餘的工作表保持不變。

ws.Columns [1].Replace("old value", "new Value")
ws.Columns [1].Replace("old value", "new Value")
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'ws.Columns [1].Replace("old value", "new Value")
VB   C#

上述程式碼將僅為第 1 列更換 old valuenew value

7.5. 替換欄位範圍的值

透過以下方式,我們也可以使用範圍函數來替換特定欄位內的範圍。

 ws ["B5:B10"].Replace("old value", "new value");
 ws ["B5:B10"].Replace("old value", "new value");
ws ("B5:B10").Replace("old value", "new value")
VB   C#

上述程式碼將把 舊值 替換為 新值,僅在 B 列從 B5B10 的範圍內。


8. 從 Excel 工作表中移除行

IronXL 提供了一個非常簡單的函數來移除 Excel 工作表中的特定行。讓我們來看看這個例子。

/**
Remove Row
anchor-remove-row-from-excel-worksheet
**/
using IronXL;
static void Main(string [] args)
{ 
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    ws.Rows [3].RemoveRow();
    wb.SaveAs("sample.xlsx");
}
/**
Remove Row
anchor-remove-row-from-excel-worksheet
**/
using IronXL;
static void Main(string [] args)
{ 
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    ws.Rows [3].RemoveRow();
    wb.SaveAs("sample.xlsx");
}
'''
'''Remove Row
'''anchor-remove-row-from-excel-worksheet
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
	Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
	ws.Rows (3).RemoveRow()
	wb.SaveAs("sample.xlsx")
End Sub
VB   C#

上述程式碼將刪除 sample.xlsx 的第 3 行,如下表所示:

Before
After

:---:
:---:

之前 之後


9. 從 Excel 檔案中移除工作表

如果我們想要移除 Excel 檔案中的完整工作表,我們可以使用以下方法:

/**
Remove Worksheet from File
anchor-remove-worksheet-from-excel-file
**/
wb.RemoveWorkSheet(1); // by sheet indexing
/**
Remove Worksheet from File
anchor-remove-worksheet-from-excel-file
**/
wb.RemoveWorkSheet(1); // by sheet indexing
'''
'''Remove Worksheet from File
'''anchor-remove-worksheet-from-excel-file
'''*
wb.RemoveWorkSheet(1) ' by sheet indexing
VB   C#

wb 是工作簿,與上述範例中的相同。如果我們想按名稱刪除工作表,則:

wb.RemoveWorkSheet("Sheet1"); //by sheet name
wb.RemoveWorkSheet("Sheet1"); //by sheet name
wb.RemoveWorkSheet("Sheet1") 'by sheet name
VB   C#

IronXL 擁有豐富的功能,我們可以輕鬆地在 Excel 工作表中進行任何類型的編輯和刪除。如果您在項目中使用時有任何問題,請隨時聯繫我們的開發團隊。


資料庫快速訪問

IronXL 遊戲庫文件

探討 IronXL C# 庫的全部功能,包括編輯、刪除、樣式設計和完善您的 Excel 工作簿的各種功能。

IronXL 遊戲庫文件