C# 编辑 Excel 文件

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

当开发人员开始用 C# 修改和编辑 Excel 文件时,必须小心谨慎,因为很容易因为一次失误而改变整个文件。依靠简单高效的代码行有助于降低出错风险,使我们更容易以编程方式编辑或删除 Excel 文件。今天,我们将通过必要的步骤,使用经过测试的函数在 C# 中正确、快速地编辑 Excel 文件。


步骤 1

1.C# 使用 IronXL 库编辑 Excel 文件

在本教程中,我们将使用 IronXL(一个 C# Excel 库)定义的函数。要使用这些函数,首先需要下载并将其安装到您的项目中 (免费开发).

您可以 下载 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 的表格结果:

之前 之后

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

之前 后


7.替换电子表格值

如果我们想用 Excel 电子表格中的更新值替换任何类型的值,可以使用名为 "替换 "的函数。使用该函数,我们可以在任何需要的情况下替换 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 工作表中用 "新值 "替换 "旧值"。

更改后请不要忘记保存文件,如上面的示例所示。

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 "中用 "新值 "替换 "旧值"。工作表的其他部分保持不变。

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#

假设我们想用新值替换旧值,替换的范围是行号 4B4E4 之间,那么我们可以这样写:

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 "的 "旧值"。

7.5.替换列范围的值

通过下面的方法,我们还可以使用 range 函数在特定列的范围内进行替换。

 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 行:

之前 之后

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

之前 后


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 库文档