跳至頁尾內容
USING IRONXL

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

以程式方式重新命名 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");
            }
        }
    }
    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
  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"));
            }
        }
    }
}
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
$vbLabelText   $csharpLabel

程式碼解釋

  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"
}

結論

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

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

常見問題

我如何在 C# 中不使用 Interop 重命名 Excel 工作表?

您可以通過使用 IronXL 程式庫在 C# 中不使用 Interop 來重命名 Excel 工作表。將您的 Excel 檔案載入到 WorkBook 物件中,選擇您希望重命名的工作表,然後通過 Name 屬性設置其新名稱。

使用IronXL進行Excel文件操作的好處是什麼?

IronXL 提供了強大的功能來操作 Excel 檔案,例如讀取、編輯和建立 Excel 檔案而不需要 Microsoft Excel 或 Interop。它支持多種格式,如 XLSX 和 CSV,提供使用者友好的 API,並允許自動化和整合到 .NET 項目中。

是否可以在 C# 中自動化 Excel 任務?

是的,使用 IronXL 程式庫,可以在 C# 中自動化各種 Excel 任務,如重命名工作表、讀取單元格值、計算合計等,所有這些都不需要 Microsoft Excel。

在 C# 項目中設置 IronXL 需要哪些步驟?

要在 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 的常見問題?

using IronXL 的常見問題通常可以通過確保正確安裝和配置程式庫來解決,檢查有無更新,並參閱官方文件以獲得特定功能的指導。

程式化重命名 Excel 工作表有什麼優勢?

程式化地重命名 Excel 工作表提高效率和可擴展性,提供一致性,無縫整合到現有工作流程中,並允許根據特定業務需求進行定制。

Curtis Chau
技術作家

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

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話