如何在 C# 中重命名 Excel 工作表
在各種應用程式中,以程式設計方式重新命名 Excel 檔案是一項常見任務。 無論您是在整理文件、自動化任務或管理資料,能夠透過程式碼重新命名 Excel 檔案都將大有裨益。 在本文中,我們將探討如何使用Iron Software的IronXL庫重新命名 Excel 檔案。
How to Rename Excel WorkSheet in C#
- 建立一個 Visual Studio 專案來重新命名 Excel 工作表。
- 從Iron Software安裝IronXL庫。
- 使用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"); } } }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"); } } }Imports IronXL Namespace RenameExcelSheets Public Class Program Public Shared Sub Main() Console.WriteLine("Rename Excel Sheets Using IronXL") ' Load an existing Excel file into a WorkBook object Dim workBook As WorkBook = WorkBook.Load("sample.xlsx") ' sample excel file ' Select the specified worksheet (first sheet) Dim workSheet As WorkSheet = workBook.WorkSheets(0) ' Read a cell value from the workbook Dim cellValue As Integer = workSheet("A2").IntValue ' Iterate through a range of cells and print their values For Each cell In workSheet("A2:A10") Console.WriteLine($"Cell {cell.AddressString} has value '{cell.Text}'") Next cell ' Calculate aggregate values Dim sum As Decimal = workSheet("A2:A10").Sum() Dim max As Decimal = workSheet("A2:A10").Max(Function(c) c.DecimalValue) ' Save as a new workbook workBook.SaveAs("sampleResult.xlsx") End Sub End Class End Namespace$vbLabelText $csharpLabel - 輕鬆掌握 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 並建立一個新的示範專案。 從以下模板中選擇"控制台"應用程式。
如何在 C# 中重新命名 Excel 工作表:圖 1 - 建立控制台應用程式
請提供專案名稱和檔案儲存路徑。
如何在 C# 中重新命名 Excel 工作表:圖 2 - 為專案命名
選擇所需的 .NET 版本。
步驟 2:從Iron Software安裝IronXL庫。
IronXL庫可以透過 Visual Studio 套件管理器安裝,如下所示。
如何在 C# 中重新命名 Excel 工作表:圖 4 - 使用 NuGet 套件管理器搜尋 IronXL
或者可以透過 NuGet 套件管理器使用命令進行安裝。
dotnet add package IronXL.Excel --version 2024.4.4
如何在 C# 中重新命名 Excel 工作表:圖 5 - IronXL 首頁
專案安裝完成後,即可開始撰寫重命名 Excel 工作表的程式碼。
步驟 3:使用IronXL重新命名 Excel 工作表
下面這個程式用來重新命名商業應用程式中目錄中的所有檔案和工作表。
輸入:
如何在 C# 中重新命名 Excel 工作表:圖 6 - 用於重新命名的 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"));
}
}
}
}
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
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: workBook.SaveAs(Path.Combine(outputPath, string.Format("FinancialReport2024_{0}.xlsx", index++)));
workBook.SaveAs(Path.Combine(outputPath, $"FinancialReport2024_{index}.xlsx"))
index += 1
Next file
End Sub
End Class
End Namespace
程式碼解釋
- 程式提示使用者輸入 Excel 檔案所在的資料夾路徑。
- 它檢查資料夾路徑是否為空字串以及資料夾是否實際存在。
- 它從指定的資料夾中檢索所有檔案。
- 它遍歷這些文件,將每個文件載入到 IronXL 庫中的 WorkBook 物件中。
- 對於每個工作簿,它會重新命名第一個工作表。
- 它將每個修改後的工作簿保存在原始資料夾內的"輸出"資料夾中。
輸出
在下面的輸出中,您可以看到所有 3 個檔案都已重新命名,並且其中的 Excel 工作表也重新命名為 FinancialReport2024。
如何在 C# 中重新命名 Excel 工作表:圖 7 - 範例輸出,顯示了使用 IronXL 重新命名的所有 Excel 工作表
以程式設計方式重新命名 Excel 工作表的優點包括:
- 效率:自動化可減少手動重命名所耗費的人力及人為錯誤,從而節省時間與資源。
- 一致性:自動重命名功能可確保跨工作表的統一性並遵循命名規範,從而提升資料的組織性與可讀性。
- 可擴展性:透過程式化方式重新命名工作表,可實現批量重命名與可擴展性,使其適合處理大型資料集或重複性任務。
- 整合:與現有工作流程或應用程式的整合,可實現無縫的資料處理,並提升整體生產力。
- 自訂功能:自動化技術提供靈活性,可依據特定的業務需求或準則自訂重新命名邏輯。
授權
IronXL 是一個企業級庫,需要簽訂授權協議才能使用。 有關許可證的更多信息,請點擊此處查看。 許可證金鑰需要放置在 appsettings.json 檔案中。
{
"IronXL.License.LicenseKey" : "IRONXL-MYLICENSE-KEY-1EF01"
}
結論
使用 C# 重新命名 Excel 檔案是一個簡單的過程。 透過利用Iron Software的IronXL庫,您可以輕鬆地在 C# 應用程式中重新命名 Excel 檔案。 該程式庫是開發人員執行所有 Excel 表格操作(無論是讀取、寫入或管理)的便利工具。
現在你已經學會如何以程式設計方式重命名 Excel 文件,你可以將此功能整合到你的 C# 專案中,以簡化文件管理任務並提高自動化能力。
常見問題解答
如何在 C# 中重命名 Excel 工作表而不使用 Interop?
您可以通過利用 IronXL 庫在 C# 中重命名 Excel 工作表,而無需使用 Interop。将您的 Excel 文件加载到 WorkBook 對象中,選择您希望重命名的工作表,然後通過 Name 属性設置其新名称。
使用IronXL進行Excel文件操作有哪些好處?
IronXL 為 Excel 文件操作提供了強大的功能,例如读取、编辑和创建 Excel 文件,無需 Microsoft Excel 或 Interop。它支持 XLSX 和 CSV 等各种格式,提供用戶友好的 API,并允許運用于 .NET 項目的自動化和集成。
在 C# 中可以自動化 Excel 任务嗎?
是的,使用 IronXL 庫,您可以在 C# 中自動化各种 Excel 任务,例如重命名工作表、读取单元格值、计算聚合等,所有这些都無需 Microsoft Excel。
設置 IronXL 以進行 C# 項目涉及哪些步驟?
要在 C# 項目中設置 IronXL,首先创建一個 Visual Studio 項目,然後使用 NuGet 包管理器安装 IronXL 庫,命令:dotnet add package IronXL.Excel --version 2024.4.4。然後您可以開始使用它的功能来操作 Excel 文件。
IronXL 可以處理多种 Excel 格式嗎?
是的,IronXL 支持多种 Excel 格式,包括 XLSX、XLS、XLSM、XLTX、CSV 和 TSV,從而為 .NET 應用程序提供多种文件操作功能。
在我的項目中使用 IronXL 需要許可證嗎?
是的,使用 IronXL 開發您的項目需要許可證。一旦您有了許可證密钥,應該将其放入您項目的 appsettings.json 文件中,以启用完整功能。
使用 IronXL 時如何排除常见問题?
使用 IronXL 時的常见問题通常可以通過确保庫正确安装和配置、检查更新,以及查阅官方文檔以獲取特定功能的指导来解决。
以编程方式重命名 Excel 工作表有哪些优势?
以编程方式重命名 Excel 工作表可以提高效率和可擴展性,提供一致性,与現有工作流無缝集成,并根据特定的业务需求進行定制。


