使用IRONXL

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

里根普恩
里根普恩
2024年4月29日
分享:

介紹

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

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

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

  2. Iron Software安裝IronXL庫。

  3. 使用IronXL重命名 Excel 工作表。

IronXL 庫來自 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 都能滿足您的需求。

    1. 用戶友好的 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
$vbLabelText   $csharpLabel
  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:從Iron Software安裝IronXL庫。

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
$vbLabelText   $csharpLabel

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

一旦安裝完成,專案就可以開始編寫代碼進行重命名 Excel 工作表。

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

以下是一個用於商務應用的程式,用來重命名目錄中的所有檔案和工作表。

輸入

如何在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
$vbLabelText   $csharpLabel

程式碼說明

  1. 取得資料夾路徑以重新命名所有文件及其工作表。

  2. 檢查資料夾路徑是否為空字串

  3. 檢查資料夾路徑是否有效

  4. 獲取文件夾中所有具有 xlsx 擴展名的文件

  5. 遍歷檔案,並從IronXL載入至WorkBook物件以重新命名工作表名稱屬性。

  6. 將檔案儲存到輸出資料夾。

    輸出

    在以下輸出中,您可以看到所有三個文件都被重新命名,其中的 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
$vbLabelText   $csharpLabel

結論

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

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

里根普恩
軟體工程師
Regan 畢業於雷丁大學,擁有電子工程學士學位。在加入 Iron Software 之前,他的工作角色讓他專注於單一任務;而他在 Iron Software 工作中最喜歡的是他所能承擔的工作範圍,無論是增加銷售價值、技術支持、產品開發或市場營銷。他喜歡了解開發人員如何使用 Iron Software 庫,並利用這些知識不斷改進文檔和開發產品。
< 上一頁
如何使用 C# 設置 Excel 字體樣式
下一個 >
如何在C#控制台應用程式中讀取Excel檔案