
如何在 C# 中重命名 Excel 工作表
以编程方式重命名 Excel 文件是在各种应用程序中的常见任务。 无论您是在组织文件、自动化任务,还是管理数据,通过代码重命名 Excel 文件的能力都可以带来极大的好处。
在本文中,我们将探讨如何使用 IronXL 库重命名 Excel 文件,来自 Iron Software。
How to Rename Excel WorkSheet in C#
- 创建一个 Visual Studio 项目以重命名 Excel 表。
2. 从 Iron Software 安装 IronXL 库。
3. 使用 IronXL 重命名 Excel 工作表。
来自Iron Software的IronXL库
IronXL 是由 Iron Software 开发的强大 C# Excel 库。
它允许您在 .NET 项目中处理 Excel 文档,而无需 Microsoft Office 或 Excel Interop。IronXL的主要特点
-
**读取、编辑和创建 Excel 文件:**IronXL 允许您直接通过 C# 或 VB.NET 代码读取、生成和编辑 Excel 电子表格文件(包括 XLSX、XLS、XLSM、XLTX、CSV 和 TSV 格式)。
-
**无需 Office 互操作:**您无需安装 Microsoft Office,也无需处理 Office 互操作的复杂性。IronXL 提供无忧的使用体验。
-
**跨平台支持:**IronXL 支持 .NET 8、7、6、Core、Framework 及 Azure。 无论您是在构建控制台应用程序、Web 应用还是桌面软件,IronXL 都能满足您的需求。
-
**用户友好的 API:**直观的 API 允许您执行读取单元格值、计算汇总值、处理公式、创建图表等任务。 让我们简要地检查一个示例:
using IronXL; namespace RenameExcelSheets { public class Program { public static void Main() { Console.WriteLine("Rename Excel Sheets Using IronXL"); // Load an existing Excel file into a WorkBook object WorkBook workBook = WorkBook.Load("sample.xlsx"); // sample excel file // Select the specified worksheet (first sheet) WorkSheet workSheet = workBook.WorkSheets[0]; // Read a cell value from the workbook int cellValue = workSheet["A2"].IntValue; // Iterate through a range of cells and print their values foreach (var cell in workSheet["A2:A10"]) { Console.WriteLine($"Cell {cell.AddressString} has value '{cell.Text}'"); } // Calculate aggregate values decimal sum = workSheet["A2:A10"].Sum(); decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue); // Save as a new workbook workBook.SaveAs("sampleResult.xlsx"); } } }C# -
**轻松掌握 Excel 功能:**IronXL 助您轻松创建、加载、保存和操作电子表格。 无论您是在处理元数据、权限、公式或样式,IronXL都简化了流程。
请记住,IronXL因其准确性、易用性和速度而受到全球数百万工程师的信赖。 如果您正在用 C# 或 VB.NET 处理 Excel 文件,IronXL 是您的首选库!
设置环境
在深入了解编码部分之前,请确保您已安装必要的工具:
- **Visual Studio:**安装 Visual Studio 或您偏好的其他 C# 集成开发环境 (IDE)。
- **Microsoft Excel:**请确保您的系统已安装 Microsoft Excel。
为了演示一个重命名 Excel 文件的实际例子,让我们编写一个程序来获取包含所有要重命名文件的文件夹,并使用 IronXL 重命名所有文件,然后将它们存储在输出文件夹中。
步骤 1:创建 Visual Studio 项目以重命名 Excel 表
打开 Visual Studio 并为演示创建一个新项目。 从下面的模板中选择控制台应用。

为项目提供名称和存储文件的路径。

选择所需的.NET版本。

步骤 2:从Iron Software安装IronXL库
IronXL 库可以通过下面的 Visual Studio 包管理器安装。

或者可以使用命令从 NuGet 包管理器中安装。

一旦安装完毕,项目即可开始编写重命名 Excel 工作表的代码。
步骤 3:使用IronXL重命名 Excel 表
以下是用于在业务应用程序中重命名目录中所有文件和工作表的程序。
输入:

using System;
using System.IO;
using IronXL;
namespace RenameExcelSheets
{
public class Program
{
public static void Main()
{
Console.WriteLine("Demo Rename Excel Sheets Using IronXL");
Console.WriteLine("Enter Folder where Excel Files are present to rename to FinancialReport2024");
// Getting input folder path from user
var folderPath = Console.ReadLine();
// Check if the provided path is not empty
if (string.IsNullOrEmpty(folderPath))
{
throw new ArgumentException("Path is empty");
}
// Check if the given folder path exists
if (!Directory.Exists(folderPath))
{
throw new ArgumentException("Path is Wrong");
}
// Get all files in the directory
var files = Directory.GetFiles(folderPath);
// Define output directory for renamed files
var outputPath = Path.Combine(folderPath, "output");
Directory.CreateDirectory(outputPath); // Ensures the output directory exists
var index = 0;
foreach (var file in files)
{
// Load an existing Excel file
WorkBook workBook = WorkBook.Load(file);
// Select the first worksheet (index 0)
WorkSheet workSheet = workBook.WorkSheets[0];
// Rename the worksheet
workSheet.Name = "FinancialReport2024"; // change the name property
// Save the modified workbook with a new name in the output folder
workBook.SaveAs(Path.Combine(outputPath, $"FinancialReport2024_{index++}.xlsx"));
}
}
}
}Imports System
Imports System.IO
Imports IronXL
Namespace RenameExcelSheets
Public Class Program
Public Shared Sub Main()
Console.WriteLine("Demo Rename Excel Sheets Using IronXL")
Console.WriteLine("Enter Folder where Excel Files are present to rename to FinancialReport2024")
' Getting input folder path from user
Dim folderPath = Console.ReadLine()
' Check if the provided path is not empty
If String.IsNullOrEmpty(folderPath) Then
Throw New ArgumentException("Path is empty")
End If
' Check if the given folder path exists
If Not Directory.Exists(folderPath) Then
Throw New ArgumentException("Path is Wrong")
End If
' Get all files in the directory
Dim files = Directory.GetFiles(folderPath)
' Define output directory for renamed files
Dim outputPath = Path.Combine(folderPath, "output")
Directory.CreateDirectory(outputPath) ' Ensures the output directory exists
Dim index = 0
For Each file In files
' Load an existing Excel file
Dim workBook As WorkBook = WorkBook.Load(file)
' Select the first worksheet (index 0)
Dim workSheet As WorkSheet = workBook.WorkSheets(0)
' Rename the worksheet
workSheet.Name = "FinancialReport2024" ' change the name property
' Save the modified workbook with a new name in the output folder
workBook.SaveAs(Path.Combine(outputPath, $"FinancialReport2024_{index}.xlsx"))
index += 1
Next
End Sub
End Class
End Namespace代码解释
- 程序提示用户输入 Excel 文件所在文件夹的路径。
- 检查文件夹路径是否为空字符串以及文件夹是否实际存在。
- 从指定文件夹中检索所有文件。
- 迭代这些文件,将每一个加载到 IronXL 库的 WorkBook 对象中。
- 对于每个工作簿,重命名第一个工作表。
- 将每个修改过的工作簿保存到原文件夹中的"输出"文件夹中。
输出
在下面的输出中,您可以看到所有 3 个文件都已重命名,并且其中的 Excel 表也已重命名为 FinancialReport2024。

以编程方式重命名 Excel 表的优点包括
- **效率:**自动化可减少手动重命名带来的工作量和人为错误,从而节省时间和资源。
- **一致性:**自动重命名可确保跨工作表的一致性并遵循命名规范,从而提升数据组织性和可读性。
- **可扩展性:**通过编程方式重命名工作表支持批量重命名并具备可扩展性,因此适用于处理大型数据集或重复性任务。
- **集成:**与现有工作流或应用程序的集成可实现无缝的数据处理,并提升整体工作效率。
- **自定义:**自动化功能提供了灵活性,可根据具体的业务需求或标准自定义重命名逻辑。
许可
IronXL 是一个企业级库,需通过许可证协议进行工作。 关于许可证的更多信息可以在这里找到。 许可证密钥需要放在此处的 appsettings.json 文件中。
{
"IronXL.License.LicenseKey" : "IRONXL-MYLICENSE-KEY-1EF01"
}
结论
using C# 重命名 Excel 文件是一个简单的过程。
通过利用 IronXL 库来自 Iron Software,您可以轻松地在您的 C# 应用程序中重命名 Excel 文件。
此库是开发人员处理所有 Excel 表操作的便利工具,无论是读取、写入还是管理。现在您已经学习了如何以编程方式重命名 Excel 文件,您可以将此功能整合到您的 C# 项目中,以简化文件管理任务并提高自动化能力。

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。
相关文章



