IRONXLの使用

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

リーガン・パン
リーガン・パン
2024年4月29日
共有:

イントロダクション

プログラムによってExcelファイルをリネームすることは、様々なアプリケーションにおいて一般的な作業です。 ファイルの整理、タスクの自動化、またはデータの管理において、コードを用いてExcelファイルの名前を変更できる能力は非常に有益です。 この記事では、IronXLライブラリを使用してExcelファイルを名前変更する方法をIron Softwareから紹介します。

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

  1. ExcelシートをリネームするためのVisual Studioプロジェクトを作成する。

  2. IronXL ライブラリを Iron Software からインストールします。

  3. IronXLを使用してExcelシートの名前を変更します。

IronXLライブラリ from Iron Software

IronXL は、Iron Software によって開発された強力なC# Excelライブラリです。 それを使用すると、Microsoft OfficeやExcel Interopを必要とせずに、.NETプロジェクトでExcelドキュメントを操作できます。

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向けに設計されています。 コンソールアプリケーション、Webアプリ、またはデスクトップソフトウェアを構築する際、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は、その正確さ、使いやすさ、そして速度のために世界中の何百万人ものエンジニアに信頼されています。 ExcelファイルをC#またはVB.NETで扱う場合、IronXLは必須のライブラリです!

環境の設定

コーディングに入る前に、必要なツールがインストールされていることを確認してください。

  1. Visual Studio: Visual Studio または任意の好みの C# IDE をインストールします。

  2. Microsoft Excel: お使いのシステムにMicrosoft Excelがインストールされていることを確認してください。

    実際の例としてExcelファイルの名前を変更するプログラムを作成してみましょう。フォルダに含まれるすべてのファイルをリネームし、IronXLを使用してそれらのファイルの名前を変更して、出力フォルダに保存するようにプログラムを書きます。

ステップ1: Excelシートの名前を変更するためのVisual Studioプロジェクトを作成します。

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

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

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

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

必要な .NET バージョンを選択してください。

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

ステップ2:IronXL ライブラリを Iron Software からインストールします。

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. ファイルを出力フォルダーに保存

    出力

    以下の出力では、3つのファイルすべての名前が変更され、それらの中の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シート操作に対応する開発者にとって便利なツールです。

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

リーガン・パン
ソフトウェアエンジニア
レーガンはリーディング大学で電子工学の学士号を取得しました。Iron Softwareに入社する前の仕事では、一つのタスクに集中して取り組んでいました。Iron Softwareでは、営業、技術サポート、製品開発、マーケティングのいずれにおいても広範な業務に携わることが最も楽しいと感じています。彼は、Iron Softwareライブラリを開発者がどのように使用しているかを理解し、その知識を使ってドキュメントを継続的に改善し、製品を開発することを楽しんでいます。
< 以前
C#でExcelフォントスタイルを使用する方法
次へ >
C#コンソールアプリケーションでExcelファイルを読み取る方法