使用IRONXL

如何在 C# 中重命名 Excel 工作表

發佈 2024年4月29日
分享:

介紹

程式化地重新命名 Excel 文件是各種應用中的常見任務。無論您是在整理文件、自動化任務還是管理數據,能夠通過程式碼重新命名 Excel 文件都會非常有利。在本文中,我們將探討如何使用 IronXL 圖書館由 Iron Software.

如何在 C# 中重命名 Excel 工作表

  1. 創建一個 Visual Studio 專案來重命名 Excel 工作表。

  2. 安裝 IronXL 圖書館由 Iron Software.

  3. 使用 IronXL.

IronXL 圖書館由 Iron Software

IronXL 是一款由開發的強大C# Excel庫 Iron Software它允許您在 .NET 專案中處理 Excel 文件,而無需使用 Microsoft Office 或 Excel Interop。

IronXL 的主要功能

  1. 讀取、編輯和創建 Excel 文件:IronXL 允許您讀取、生成和編輯 Excel 試算表文件 (包括 XLSX、XLS、XLSM、XLTX、CSV 和 TSV 格式) 直接從您的C#或VB.NET程式碼中。

  2. 不需要 Office Interop:您無需安裝 Microsoft Office 或處理 Office Interop 的複雜性。IronXL 提供無憂的使用體驗。

  3. 跨平台支援:IronXL 專為 .NET 8、7、6、Core、Framework 和 Azure 設計。無論您在構建控制台應用程序、Web 應用程序還是桌面軟件,IronXL 都能滿足您的需求。

  4. 用戶友好的 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 to excel workbook object
            WorkBook workBook = WorkBook.Load("sample.xlsx"); // sample excel file
            // Select specified worksheet
            WorkSheet workSheet = workBook.WorkSheets [0];
            // Read a cell value from same workbook
            int cellValue = workSheet ["A2"].IntValue;
            // Iterate through a range of cells
            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);
            workBook.SaveAs("sampleResult.xlsx"); // save as new workbook
        }
    }
using IronXL;
    namespace RenameExcelSheets;
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("Rename Excel Sheets Using IronXL");
            // Load an existing Excel file to excel workbook object
            WorkBook workBook = WorkBook.Load("sample.xlsx"); // sample excel file
            // Select specified worksheet
            WorkSheet workSheet = workBook.WorkSheets [0];
            // Read a cell value from same workbook
            int cellValue = workSheet ["A2"].IntValue;
            // Iterate through a range of cells
            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);
            workBook.SaveAs("sampleResult.xlsx"); // save as new workbook
        }
    }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. 沒有麻煩的 Excel 功能:IronXL 讓您能夠輕鬆地建立、載入、儲存和操作試算表。無論您是在處理元數據、權限、公式還是樣式,IronXL 都能簡化這個過程。

請記住,IronXL 因其準確性、易用性和速度而得到全球數百萬工程師的信任。如果您在使用 C# 或 VB.NET 處理 Excel 文件,IronXL 是您的首選庫。!

設置環境

在進入編碼部分之前,請確保已安裝必要的工具:

  1. Visual Studio:安裝 Visual Studio 或其他首選的 C# IDE。
  2. Microsoft Excel:確保系統上已安裝 Microsoft Excel。

為了展示重命名 Excel 文件的實際例子,讓我們編寫一個程序,將包含所有要重命名文件的文件夾作為輸入,然後使用 IronXL 重命名所有文件,並將它們存儲在輸出文件夾中。

步驟 1:建立 Visual Studio 專案以重新命名 Excel 工作表

開啟 Visual Studio 並創建一個新的項目用於示範。從以下模板中選擇主控台應用程式。

如何在 C# 中重命名 Excel 工作表:圖 1 - 建立一個控制台應用程式

請為專案提供名稱及存放檔案的路徑。

如何在 C# 中重新命名 Excel 工作表:圖 2 - 為專案命名

選擇所需的 .NET 版本。

如何在 C# 中重命名 Excel 工作表:圖 3 - 選擇所需的 .NET 版本

步驟 2:安裝 IronXL 圖書館由 Iron Software.

IronXL 可以從 Visual Studio 套件管理器安裝該函式庫,如下所示。

如何在 C# 中重命名 Excel 工作表:圖 4 - 使用 NuGet 套件管理器搜索 IronXL

或可以使用以下指令從 NuGet 套件管理器安裝。

dotnet add package IronXL.Excel --version 2024.4.4
dotnet add package IronXL.Excel --version 2024.4.4
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronXL.Excel --version 2024.4.4
VB   C#

如何在 C# 中重命名 Excel 工作表:圖 5 - IronXL 首頁

安裝完成後,專案就準備開始編寫代碼來重新命名 Excel 工作表。

步驟3:使用重命名Excel工作表 IronXL

以下是將目錄中的所有檔案和工作表重新命名以供商業應用的程式。

輸入

如何在 C# 中重命名 Excel 工作表:圖 6 - 重命名範例 Excel 工作表輸入

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");
        var folderPath = Console.ReadLine();
        if (string.IsNullOrEmpty(folderPath)) // check for empty string
        {
            throw new AggregateException("Path is empty");
        }
        if (Directory.Exists(folderPath) == false)
        {
            throw new AggregateException("Path is Wrong");
        }
        var files = Directory.GetFiles(folderPath);
        var outputPath = Path.Combine(folderPath, "output");
        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
            workBook.SaveAs(Path.Join(outputPath, $"FinancialReport2024_{index++}.xlsx"));
        }
    }
}
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");
        var folderPath = Console.ReadLine();
        if (string.IsNullOrEmpty(folderPath)) // check for empty string
        {
            throw new AggregateException("Path is empty");
        }
        if (Directory.Exists(folderPath) == false)
        {
            throw new AggregateException("Path is Wrong");
        }
        var files = Directory.GetFiles(folderPath);
        var outputPath = Path.Combine(folderPath, "output");
        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
            workBook.SaveAs(Path.Join(outputPath, $"FinancialReport2024_{index++}.xlsx"));
        }
    }
}
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")
			Dim folderPath = Console.ReadLine()
			If String.IsNullOrEmpty(folderPath) Then ' check for empty string
				Throw New AggregateException("Path is empty")
			End If
			If Directory.Exists(folderPath) = False Then
				Throw New AggregateException("Path is Wrong")
			End If
			Dim files = Directory.GetFiles(folderPath)
			Dim outputPath = Path.Combine(folderPath, "output")
			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
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: workBook.SaveAs(Path.Join(outputPath, string.Format("FinancialReport2024_{0}.xlsx", index++)));
				workBook.SaveAs(Path.Join(outputPath, $"FinancialReport2024_{index}.xlsx"))
				index += 1
			Next file
		End Sub
	End Class
End Namespace
VB   C#

代碼說明

  1. 獲取資料夾路徑以重新命名所有文件及其工作表
  2. 檢查資料夾路徑是否為空字符串
  3. 檢查資料夾路徑是否有效
  4. 獲取資料夾中所有擴展名為 xlsx 的文件
  5. 遍歷文件並從 IronXL 加載到 WorkBook 對象以重新命名工作表名稱屬性
  6. 將文件保存到輸出資料夾

輸出

在以下輸出中,您可以看到所有3個文件均已重新命名,且其中的Excel表單也被重新命名為 FinancialReport2024。

如何在 C# 中重新命名 Excel 工作表:圖 7 - 使用 IronXL 將所有 Excel 工作表重新命名的示例輸出

程式化重命名 Excel 工作表的優勢包括

  • 效率: 自動化減少了手動重命名所需的人工努力和人為錯誤,從而節省時間和資源。
  • 一致性: 自動化重命名確保了跨工作表的名稱統一和遵循命名規則,提升數據組織和可讀性。
  • 可擴展性: 程式化的重命名允許批量重命名和擴展性,適合處理大型數據集或重複任務。
  • 整合: 與現有工作流程或應用程式的整合能實現無縫數據處理,並提高整體生產力。
  • 自訂化: 自動化提供了根據具體業務需求或標準自訂重命名邏輯的靈活性。

授權

IronXL 是一個企業級庫,遵循授權協議運作。更多關於授權的資訊可以在 這裡需將授權金鑰放置於appsettings.json檔案中。

{
  "IronXL.License.LicenseKey" : "IRONXL-MYLICENSE-KEY-1EF01"
}
{
  "IronXL.License.LicenseKey" : "IRONXL-MYLICENSE-KEY-1EF01"
}
If True Then
  "IronXL.License.LicenseKey" : "IRONXL-MYLICENSE-KEY-1EF01"
End If
VB   C#

結論

使用C#重命名Excel文件是一個簡單的過程。通過利用 IronXL 圖書館由 Iron Software您可以輕鬆地在 C# 應用程式中重新命名 Excel 文件。該庫是開發人員進行所有 Excel 表格操作的便捷工具,無論是讀取、寫入或管理文件。

既然您已經學會如何以程式化方式重新命名 Excel 文件,您可以將此功能整合到您的 C# 專案中,以簡化文件管理任務並提升自動化能力。

< 上一頁
如何使用 C# 設置 Excel 字體樣式
下一個 >
如何在C#控制台應用程式中讀取Excel檔案

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 1,023,839 查看許可證 >