Przejdź do treści stopki
KORZYSTANIE Z IRONXL

Jak zmienić nazwę arkusza Excel w języku C#

Renaming Excel files programmatically is a common task in various applications. Whether you're organizing files, automating tasks, or managing data, having the ability to rename Excel files through code can be highly beneficial. In this article, we'll explore how to rename Excel files using IronXL library from Iron Software.

How to Rename Excel WorkSheet in C

  1. Create a Visual Studio Project to rename Excel sheets.
  2. Install IronXL library from Iron Software.
  3. Rename Excel sheets using IronXL.

IronXL library from Iron Software

IronXL is a powerful C# Excel library developed by Iron Software. It allows you to work with Excel documents in your .NET projects without the need for Microsoft Office or Excel Interop.

Najważniejsze cechy IronXL

  1. Read, Edit, and Create Excel Files: IronXL enables you to read, generate, and edit Excel spreadsheet files (including XLSX, XLS, XLSM, XLTX, CSV, and TSV formats) directly from your C# or VB.NET code.
  2. No Office Interop Required: You won't need to install Microsoft Office or deal with the complexities of Office Interop. IronXL provides a hassle-free experience.
  3. Cross-Platform Support: IronXL is designed for .NET 8, 7, 6, Core, Framework, and Azure. Whether you're building console applications, web apps, or desktop software, IronXL has you covered.
  4. User-Friendly API: The intuitive API allows you to perform tasks like reading cell values, calculating aggregate values, working with formulas, creating charts, and more. Let's briefly examine an example:

    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 Functionality Without the Hassle: IronXL allows you to create, load, save, and manipulate spreadsheets effortlessly. Whether you're dealing with metadata, permissions, formulas, or styling, IronXL simplifies the process.

Remember, IronXL is trusted by millions of engineers worldwide for its accuracy, ease of use, and speed. If you're working with Excel files in C# or VB.NET, IronXL is your go-to library!

Setting Up the Environment

Before diving into the coding part, make sure you have the necessary tools installed:

  1. Visual Studio: Install Visual Studio or any other preferred C# IDE.
  2. Microsoft Excel: Make sure Microsoft Excel is installed on your system.

To demonstrate a real-world example of renaming an Excel file, let us write a program to take a folder containing all the files to rename and use IronXL to rename all the files, then store them in the output folder.

Step 1: Create Visual Studio Project to rename Excel sheets.

Open Visual Studio and create a new project for the demo. Select Console app from the below template.

How to Rename Excel WorkSheet in C#: Figure 1 - Creating a Console app

Provide names to the Project and path to store the files.

How to Rename Excel WorkSheet in C#: Figure 2 - Name the project

Select the required .NET version.

How to Rename Excel WorkSheet in C#: Figure 3 - Select the required .NET version

Step 2: Install IronXL library from Iron Software.

IronXL library can be installed from Visual Studio Package manager as below.

How to Rename Excel WorkSheet in C#: Figure 4 - Searching for IronXL using NuGet Package Manager

Or can be installed from NuGet Package Manager with command.

dotnet add package IronXl.Excel --version 2024.4.4

How to Rename Excel WorkSheet in C#: Figure 5 - IronXL homepage

Once installed the project is ready to start coding for renaming Excel worksheets.

Step 3: Rename Excel sheets using IronXL

Below is the program to rename all the files and worksheets in a directory for business applications.

Input:

How to Rename Excel WorkSheet in C#: Figure 6 - Example Excel worksheet input for renaming

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

Wyjaśnienie kodu

  1. The program prompts the user to enter a folder path where Excel files are located.
  2. It checks if the folder path is an empty string and if the folder actually exists.
  3. It retrieves all the files from the specified folder.
  4. It iterates through these files, loading each one into a WorkBook object from the IronXL library.
  5. For each workbook, it renames the first worksheet.
  6. It saves each modified workbook in an "output" folder within the original folder.

Output

In the below output, you can see all the 3 files are renamed and the Excel sheet inside them is also renamed to FinancialReport2024.

How to Rename Excel WorkSheet in C#: Figure 7 - Example output showcasing all the Excel worksheets being renamed using IronXL

Advantages of renaming Excel sheets programmatically include

  • Efficiency: Automation reduces manual effort and human errors associated with manual renaming, saving time and resources.
  • Consistency: Automated renaming ensures uniformity and adherence to naming conventions across sheets, enhancing data organization and readability.
  • Scałability: Programmatically renaming sheets allows for bulk renaming and scałability, making it suitable for handling large datasets or repetitive tasks.
  • Integration: Integration with existing workflows or applications enables seamless data processing and enhances overall productivity.
  • Customization: Automation provides flexibility to customize renaming logic based on specific business requirements or criteria.

Licensing

IronXL is an enterprise library that works with a license agreement. More on license can be found here. The license key needs to be placed in the appsettings.json file here.

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

Wnioski

Renaming Excel files using C# is a straightforward process. By leveraging the IronXL library from Iron Software, you can easily rename Excel files within your C# applications. This library is a handy tool for developers for all Excel sheet operations, be it reading, writing, or managing.

Now that you've learned how to rename Excel files programmatically, you can incorporate this feature into your C# projects to streamline file management tasks and improve automation capabilities.

Często Zadawane Pytania

Jak mogę zmienić nazwę arkusza Excel w języku C# bez użycia Interop?

Możesz zmienić nazwę arkusza Excel w języku C# bez użycia Interop, korzystając z biblioteki IronXL. Załaduj plik Excel do obiektu WorkBook, wybierz arkusz, którego nazwę chcesz zmienić, i ustaw jego nową nazwę za pomocą właściwości Name.

Jakie są zalety korzystania z IronXL do manipulacji plikami Excel?

IronXL zapewnia zaawansowane możliwości manipulacji plikami Excel, takie jak odczyt, edycja i tworzenie plików Excel bez konieczności korzystania z programu Microsoft Excel lub Interop. Obsługuje różne formaty, takie jak XLSX i CSV, oferuje przyjazny dla użytkownika interfejs API oraz umożliwia automatyzację i integrację z projektami .NET.

Czy można zautomatyzować zadania w Excelu w języku C#?

Tak, korzystając z biblioteki IronXL, można zautomatyzować różne zadania programu Excel w języku C#, takie jak zmiana nazw arkuszy, odczytywanie wartości komórek, obliczanie sum i wiele innych, a wszystko to bez konieczności korzystania z programu Microsoft Excel.

Jakie kroki należy wykonać, aby skonfigurować IronXL dla projektu C#?

Aby skonfigurować IronXL w projekcie C#, należy najpierw utworzyć projekt Visual Studio, a następnie zainstalować bibliotekę IronXL za pomocą menedżera pakietów NuGet, używając polecenia: dotnet add package IronXl.Excel --version 2024.4.4. Następnie można zacząć korzystać z jej funkcji do manipulowania plikami Excel.

Czy IronXL obsługuje wiele formatów Excel?

Tak, IronXL obsługuje wiele formatów Excel, w tym XLSX, XLS, XLSM, XLTX, CSV i TSV, co pozwala na różnorodne możliwości manipulacji plikami w aplikacjach .NET.

Czy potrzebuję licencji, aby używać IronXL w moim projekcie?

Tak, do korzystania z IronXL w projekcie wymagana jest licencja. Po uzyskaniu klucza licencyjnego należy umieścić go w pliku appsettings.json projektu, aby umożliwić pełną funkcjonalność.

Jak rozwiązywać typowe problemy podczas korzystania z IronXL?

Typowe problemy związane z używaniem IronXL można często rozwiązać, upewniając się, że biblioteka jest poprawnie zainstalowana i skonfigurowana, sprawdzając dostępność aktualizacji oraz zapoznając się z oficjalną dokumentacją w celu uzyskania wskazówek dotyczących konkretnych funkcji.

Jakie korzyści daje programowa zmiana nazw arkuszy w Excelu?

Programowa zmiana nazw arkuszy Excel poprawia wydajność i skalowalność, zapewnia spójność, płynnie integruje się z istniejącymi procesami pracy oraz umożliwia dostosowanie do konkretnych potrzeb biznesowych.

Jordi Bardia
Inżynier oprogramowania
Jordi jest najbardziej biegły w Pythonie, C# i C++. Kiedy nie wykorzystuje swoich umiejętności w Iron Software, programuje gry. Dzieląc odpowiedzialność za testowanie produktów, rozwój produktów i badania, Jordi wnosi ogromną wartość do ciągłej poprawy produktów. Różnorodne doświadczenia ...
Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie