跳至頁尾內容
使用 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 工作表

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

輸入:

如何在 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"));
            }
        }
    }
}
$vbLabelText   $csharpLabel

程式碼解釋

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

輸出

在下面的輸出中,您可以看到所有 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 工作表?

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

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

IronXL 提供強大的 Excel 檔案操作功能,無需 Microsoft Excel 或 Interop 即可讀取、編輯和建立 Excel 檔案。它支援多種格式,例如 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 工作表可以提高效率和可擴展性,提供一致性,與現有工作流程無縫集成,並允許根據特定的業務需求進行自訂。

喬迪·巴迪亞
軟體工程師
喬迪精通Python、C#和C++,除了在Iron Software運用這些技能外,他還從事遊戲程式設計。他參與產品測試、產品開發和研究等工作,為產品的持續改進做出了巨大貢獻。豐富的經驗讓他始終保持挑戰性和工作熱情,他表示這是他最喜歡在Iron Software工作的原因之一。喬迪在佛羅裡達州邁阿密長大,畢業於佛羅裡達大學,主修電腦科學和統計學。