フッターコンテンツにスキップ
IRONXLの使用

C#でExcelワークシートの名前を変更する方法

Excelファイルの名前をプログラムで変更することは、さまざまなアプリケーションで一般的なタスクです。 ファイルの整理、タスクの自動化、データの管理など、コードを通じてExcelファイルの名前を変更できることは非常に有益です。 In this article, we'll explore how to rename Excel files using IronXL library from Iron Softwareによって開発された強力なC#用のExcelライブラリです。

Excelワークシートの名前をC#で変更する方法

  1. Excelシートの名前を変更するためのVisual Studioプロジェクトを作成します。
  2. Install IronXL library from Iron Softwareによって開発された強力なC#用のExcelライブラリです。
  3. IronXLを使用してExcelシートの名前を変更します。

IronXL library from Iron Software

IronXL is a powerful C# Excel library developed by Iron Softwareによって開発された強力なC#用のExcelライブラリです。 これにより、Microsoft OfficeやExcel Interopを必要とせずに、あなたの.NETプロジェクト内でExcelドキュメントを操作することができます。

IronXLの主な機能

  1. Excelファイルの読み取り、編集、作成: IronXLは、あなたのC#またはVB.NETコードから直接、XLSX、XLS、XLSM、XLTX、CSV、およびTSV形式のExcelスプレッドシートファイルを読み取り、生成および編集できます。
  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: Excelシートの名前を変更するVisual Studioプロジェクトの作成。

Visual Studioを開いて、デモ用の新しいプロジェクトを作成します。 以下のテンプレートからコンソールアプリを選択します。

Excelワークシートの名前をC#で変更する方法: 図1 - コンソールアプリの作成

プロジェクトに名前を付け、ファイルを保存するパスを提供します。

Excelワークシートの名前をC#で変更する方法: 図2 - プロジェクトに名前を付ける

必要な.NETバージョンを選択します。

Excelワークシートの名前をC#で変更する方法: 図3 - 必要な.NETバージョンを選択します

Step 2: Install IronXL library from Iron Softwareによって開発された強力なC#用のExcelライブラリです。

IronXLライブラリはVisual Studioのパッケージマネージャーから以下のようにインストールできます。

Excelワークシートの名前をC#で変更する方法: 図4 - NuGetパッケージマネージャーからIronXLを検索する

またはNuGetパッケージマネージャーからコマンドを使用してインストールできます。

dotnet add package IronXL.Excel --version 2024.4.4

Excelワークシートの名前をC#で変更する方法: 図5 - IronXLホームページ

インストールが完了すると、Excelワークシートの名前を変更するためのコーディングを開始する準備が整います。

ステップ3: IronXLを使用してExcelシートの名前を変更する

以下は、ビジネス用途のディレクトリ内のすべてのファイルとワークシートの名前を変更するプログラムです。

入力:

Excelワークシートの名前をC#で変更する方法: 図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に名前が変更されていることがわかります。

Excelワークシートの名前をC#で変更する方法: 図7 - IronXLを使用してすべてのExcelワークシートが名前変更された例の出力

Excelシートの名前をプログラムで変更することの利点

  • 効率性: 自動化により手動の労力と手動名前変更に伴う人的エラーが削減され、時間とリソースを節約できます。
  • 一貫性: 自動化された名前変更により、シート間での一貫性と命名規則の遵守が保証され、データの整理と読みやすさが向上します。
  • スケーラビリティ: シートのプログラム上の名前変更は、大量のデータセットや反復タスクの処理に適しており、大規模な名前変更やスケーラビリティを可能にします。
  • 統合: 既存のワークフローまたはアプリケーションとの統合により、シームレスなデータ処理が可能になり、全体的な生産性が向上します。
  • カスタマイズ: 自動化により、特定のビジネス要件や基準に基づいて名前変更ロジックを柔軟にカスタマイズできます。

ライセンス

IronXLはライセンス契約に基づいて動作するエンタープライズライブラリです。 ライセンスについての詳細はこちらをご覧ください。 ライセンスキーはここでappsettings.jsonファイルに配置する必要があります。

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

結論

C#を使用したExcelファイルの名前変更は簡単なプロセスです。 By leveraging the IronXL library from Iron Software, you can easily rename Excel files within your C# applications. このライブラリは、読み取り、書き込み、管理など、すべてのExcelシート操作に便利なツールです。

プログラムでExcelファイルの名前を変更する方法を学んだ今、この機能をC#プロジェクトに組み込んで、ファイル管理タスクを効率化し、自動化能力を向上させることができます。

よくある質問

C#で Interop を使用せずに Excel ワークシートの名前を変更するにはどうすればよいですか?

IronXL ライブラリを利用することで、C# で Interop を使用せずに Excel ワークシートの名前を変更することができます。Excel ファイルをWorkBookオブジェクトにロードし、名前を変更したいワークシートを選択し、Nameプロパティを介して新しい名前を設定します。

Excelファイル操作にIronXLを使用する利点は何ですか?

IronXL は、Microsoft Excel または Interop を必要とせずに、Excel ファイルの読み取り、編集、作成などの強力な機能を提供します。XLSX や CSV などのさまざまな形式をサポートしており、ユーザーフレンドリーな API を提供することで、.NET プロジェクトへの自動化と統合が可能です。

C# で Excel のタスクを自動化することは可能ですか?

はい、IronXL ライブラリを使用することで、Microsoft Excel を必要とせずに、C# でワークシートの名前変更、セル値の読み取り、集計の計算など、さまざまな Excel タスクを自動化することができます。

C# プロジェクトのために IronXL を設定する手順はどのようなものですか?

C# プロジェクトに IronXL を設定するには、まず Visual Studio プロジェクトを作成し、NuGet パッケージマネージャーを使用して、コマンド: dotnet add package IronXL.Excel --version 2024.4.4 を実行して IronXL ライブラリをインストールします。その後、Excel ファイルを操作する機能を利用できます。

IronXL は複数の Excel 形式を処理できますか?

はい、IronXL は XLSX、XLS、XLSM、XLTX、CSV、TSV などの複数の Excel 形式をサポートしており、.NET アプリケーションで多様なファイル操作機能を可能にします。

プロジェクトで IronXL を使用するにはライセンスが必要ですか?

はい、プロジェクトで IronXL を使用するにはライセンスが必要です。ライセンスキーを取得したら、プロジェクトのappsettings.jsonファイルに配置し、完全な機能を有効にします。

IronXL を使用する際の一般的な問題をトラブルシューティングするにはどうすればよいですか?

IronXL を使用する際の一般的な問題は、ライブラリが正しくインストールおよび構成されていることを確認し、更新プログラムを確認し、特定の機能に関する公式ドキュメントを参照することで解決できることが多いです。

Excel ワークシートの名前をプログラム的に変更することにはどのような利点がありますか?

Excel ワークシートの名前をプログラム的に変更することで、効率とスケーラビリティが向上し、一貫性が確保され、既存のワークフローとシームレスに統合でき、特定のビジネスニーズに基づいてカスタマイズが可能になります。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。