跳過到頁腳內容
使用 IRONXL

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

在各種應用程式中,以程式設計方式重新命名 Excel 檔案是一項常見任務。 無論您是在整理文件、自動化任務或管理數據,能夠透過程式碼重新命名 Excel 檔案都將大有裨益。 在本文中,我們將探討如何使用Iron SoftwareIronXL庫重新命名 Excel 檔案。

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

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

Iron SoftwareIronXL

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 互通:您無需安裝 Microsoft Office 或處理 Office 互通的複雜性。 IronXL 提供輕鬆便捷的使用體驗。 3.跨平台支援:IronXL 專為 .NET 8、7、6、Core、Framework 和 Azure 設計。 無論您是建立控制台應用程式、Web 應用程式還是桌面軟體,IronXL 都能滿足您的需求。 4.使用者友善的 API :直覺的 API 可讓您執行諸如讀取儲存格值、計算聚合值、使用公式、建立圖表等任務。 讓我們簡要來看一個例子:

```csharp
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");
        }
    }
}
```

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 工作表

下面這個程式用來重新命名商業應用程式中目錄中的所有檔案和工作表。

Input:

如何在 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"
}

結論

使用 C# 重新命名 Excel 檔案是一個簡單的過程。 透過利用Iron SoftwareIronXL庫,您可以輕鬆地在 C# 應用程式中重新命名 Excel 檔案。 該程式庫是開發人員執行所有 Excel 表格操作(無論是讀取、寫入或管理)的便利工具。

現在你已經學會如何以程式設計方式重命名 Excel 文件,你可以將此功能整合到你的 C# 專案中,以簡化文件管理任務並提高自動化能力。

常見問題解答

在不使用 Interop 的情況下,如何在 C# 中重新命名 Excel 工作表?

您可以利用 IronXL.Excel 函式庫,在 C# 中重新命名 Excel 工作表,而無需使用 Interop。將 Excel 檔案載入 WorkBook 物件,選擇您要重新命名的工作表,並透過 Name 屬性設定其新名稱。

使用 IronXL.Excel 處理 Excel 檔案有哪些好處?

IronXL.Excel 提供強大的 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 時,如何排除常見問題?

使用 IronXL 時的常見問題通常可透過確保正確安裝和設定程式庫、檢查是否有任何更新,以及參考官方文件以取得特定功能的指引來解決。

程式化重命名 Excel 工作表有哪些優點?

以程式化方式重新命名 Excel 工作表可提高效率和擴充性、提供一致性、與現有工作流程無縫整合,並允許根據特定業務需求進行客製化。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。