IRONSOFTWAREHOME
USING IRONXL

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

Curtis Chau
Curtis Chau
Updated: 2026年5月8日

以程式方式重新命名 Excel 文件是各種應用程式中的常見任務。 無論是組織檔案、自動化任務還是管理資料,通過程式碼重新命名 Excel 文件的能力都可帶來極大益處。 在本文中,我們將探討如何使用IronXL程式庫從Iron Software重新命名 Excel 文件。

How to Rename Excel WorkSheet in C#

  1. 建立一個 Visual Studio 專案以重新命名 Excel 工作表。
  2. Iron Software安裝IronXL程式庫。
  3. 使用IronXL重新命名 Excel 工作表。

IronXL library from Iron Software

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

IronXL的關鍵特點

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

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

  3. **跨平台支持:**IronXL 為 .NET 8、7、6、Core、Framework 和 Azure 設計。 無論您在建立控制台應用程式、網頁應用程式還是桌面軟體,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 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#
  5. **輕鬆實現 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:從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"));
            }
        }
    }
}

程式碼解釋

  1. 程式提示使用者輸入 Excel 文件所位於資料夾的路徑。
  2. 它檢查資料夾路徑是否為空字串,並檢查資料夾是否實際存在。
  3. 它從指定資料夾中檢索所有文件。
  4. 它遍及這些文件,並將每一個文件載入到 IronXL 程式庫的 WorkBook 物件中。
  5. 對於每個工作簿,它會重命名第一個工作表。
  6. 它將每個修改過的工作簿保存到原資料夾中的 "output" 資料夾中。

輸出

在下面的輸出中,您可以看到所有的3個文件都已重命名,並且其中的 Excel 工作表也已重命名為 FinancialReport2024。

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

以程式方式重新命名 Excel 工作表的優點包括

  • **效率:**自動化減少與手動重命名相關的人工努力和人為錯誤,節省時間和資源。
  • **一致性:**自動重命名確保工作表之間的一致性和命名慣例的遵循,增強資料組織和可讀性。
  • **可擴展性:**以程式方式重新命名工作表允許大量重命名和可擴展性,適合處理大型資料集或重複任務。
  • **整合:**與現有工作流程或應用程式的整合可實現無縫的資料處理並提高整體生產力。
  • **自訂:**自動化提供了根據特定業務需求或標準自訂重命名邏輯的靈活性。

授權

IronXL 是一個企業級程式庫,適用於授權協議。 有關授權的更多資訊可以在這裡找到。 授權金鑰需要放置在此 appsettings.json 檔案中。

{
  "IronXL.License.LicenseKey" : "IRONXL-MYLICENSE-KEY-1EF01"
}
JSON

結論

using C# 重新命名 Excel 文件是一個簡單明瞭的過程。 通過利用來自Iron SoftwareIronXL程式庫,您可以輕鬆地在您的 C# 應用程式中重新命名 Excel 文件。 這個程式庫是開發人員處理所有 Excel 工作表操作的便捷工具,不論是讀取、寫入還是管理。

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

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預約您的免費即時演示
Booking Badge

全球數百萬工程師的信賴

Iron Software的客戶標誌
獲得無義務諮詢
填寫以下表格或電郵sales@ironsoftware.com
您的資料將始終保密。
全球數百萬工程師的信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立