フッターコンテンツにスキップ
IRONWORDの使用方法

C#でワードテンプレートを使用してワード文書を生成する方法

現代のアプリケーションでは、請求書、納品書、手紙などのさまざまな目的で Word 文書を即座に生成することが重要です。Microsoft Word テンプレート ドキュメント機能は、一貫性と効率性を確保するための強力な方法を提供します。 ただし、これらのテンプレートに手動で入力すると時間がかかり、エラーが発生しやすくなります。 ここで、 Iron SoftwareIronWordが登場します。これは、Word テンプレートにデータを入力するプロセスをプログラムで自動化するように設計された強力な .NET ライブラリです。 この記事では、 IronWordを使用して Word 文書テンプレートに入力する方法を説明し、そのプロセスを示す実際の例を示します。

C#でWordテンプレートを使用してWord文書を生成する方法

  1. Microsoft Visual Studio で新しいプロジェクトを作成します。
  2. NuGet パッケージ マネージャーを使用してIronWordをインストールします。
  3. Word テンプレート文書を作成します。
  4. Word 文書にデータを挿入し、新しいファイルとして保存します。
  5. 生成された Word 文書にテキスト効果を追加します。

IronWordとは何ですか?

IronWord は、Microsoft Word ドキュメントをプログラムで簡単に作成、操作、管理できるように設計されたIron Softwareの .NET ライブラリです。 これにより、開発者は Word 文書の生成プロセスを自動化できるため、アプリケーション内でレポート、請求書、手紙、その他の種類の文書を動的に作成することが容易になります。

IronWord の主要機能

1. C# Wordテンプレートの記入と処理

IronWord では、Word テンプレートを使用してテンプレート ドキュメント内のプレースホルダーを定義し、実行時に実際のデータに置き換えることができます。

2. テキスト操作

Word ドキュメント内のテキストを簡単に挿入、置換、または削除できます。

3. 書式設定

ライブラリは、フォント スタイル、サイズ、色、段落の配置など、さまざまな書式設定オプションをサポートしています。

4. 表と画像

IronWord を使用すると、ドキュメント内に表や画像を挿入したり操作したりできます。

5. 互換性

異なるバージョンの Microsoft Word とシームレスに動作し、互換性と使いやすさを確保します。

使用例

*レポート生成: 動的なデータを使用して詳細なレポートを自動的に生成します。

  • 請求書作成: 顧客情報や取引明細を入力してプロフェッショナルな請求書を作成します。
  • 契約管理: 個別の情報を使用した契約書の作成を自動化します。
  • 手紙や通知: クライアントや従業員のために個人用の手紙や通知を生成します。

IronWord は、.NET アプリケーションでの Word ドキュメント作業を簡素化し、ドキュメント生成や管理のタスクを自動化したい開発者にとって貴重なツールとなります。

前提条件

始める前に以下を確認してください:

  • マシンに Visual Studio がインストールされている。
  • 最新の .NET フレームワークがインストールされている。

ステップ 1: Microsoft Visual Studio で新しいプロジェクトを作成します。

では、新しい Visual Studio プロジェクトを作成することから始めましょう。

C#でWordテンプレートを使用してWord文書を生成する方法: 図1

以下の画面でコンソール アプリケーション テンプレートを選択します。

C#でWordテンプレートを使用してWord文書を生成する方法: 図2 - コンソールアプリの選択

プロジェクト名と場所を指定します。

C#でWordテンプレートを使用してWord文書を生成する方法: 図3 - 名前と場所を指定する

できれば最新のサポート付きの .NET バージョンを選択し、"作成"をクリックします。

C#でWordテンプレートを使用してWord文書を生成する方法: 図4

ステップ 2: IronWord NuGet パッケージ マネージャーをインストールします。

Visual Studio で以下のように NuGet パッケージ マネージャーから IronWord NuGet パッケージをインストールします。

C#でWordテンプレートを使用してWord文書を生成する方法: 図5 - NuGetパッケージマネージャーからIronWordを検索

あるいは、以下のコマンドを使用して、CLI から直接インストールしてください。

dotnet add package IronWord --version 2024.9.1
dotnet add package IronWord --version 2024.9.1
SHELL

ステップ 3: Word テンプレート ドキュメントを作成します。

次に、Word ドキュメント生成プロセス中に使用される 1 ページまたは 2 ページの Word テンプレート ドキュメントを生成します。

Dear {Name},

Thanks for purchasing {product}. We are happy to serve you always. Your application dated {Date} has been approved. The product comes with an expiry date of {expiryDate}. Renew the product on or before the expiry date.

Feel free to contact {phone} or {email} for further queries.

Address: {Address}

Thank you,

{Sender}

次に、上記のドキュメントをTemplate.docxとして保存します。

ステップ 4: Word 文書にデータを挿入し、新しいファイルとして保存します。

using System;
using System.Collections.Generic;
using IronWord;

class Program
{
    static void Main()
    {
        // Set the license key for IronWord
        License.LicenseKey = "your key";

        // Define paths for the template and the output file
        string templatePath = "Template.docx";
        string outputPath = "FilledDocument.docx";

        // Create a new instance of the WordDocument class using the template path
        WordDocument doc = new WordDocument(templatePath);

        // Define a dictionary of placeholders and their replacements
        var replacements = new Dictionary<string, string>
        {
            { "{Name}", "John Doe" },
            { "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
            { "{Address}", "123 Iron Street, Iron Software" },
            { "{product}", "IronWord" },
            { "{Sender}", "IronSoftware" },
            { "{phone}", "+123 456789" },
            { "{email}", "sale@ironsoftware.com" },
            { "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
        };

        // Replace placeholders in the document with actual data
        foreach (var replacement in replacements)
        {
            doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
        }

        // Save the filled document
        doc.Save(outputPath);

        // Notify the user that the document has been saved successfully
        Console.WriteLine("Document filled and saved successfully.");
    }
}
using System;
using System.Collections.Generic;
using IronWord;

class Program
{
    static void Main()
    {
        // Set the license key for IronWord
        License.LicenseKey = "your key";

        // Define paths for the template and the output file
        string templatePath = "Template.docx";
        string outputPath = "FilledDocument.docx";

        // Create a new instance of the WordDocument class using the template path
        WordDocument doc = new WordDocument(templatePath);

        // Define a dictionary of placeholders and their replacements
        var replacements = new Dictionary<string, string>
        {
            { "{Name}", "John Doe" },
            { "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
            { "{Address}", "123 Iron Street, Iron Software" },
            { "{product}", "IronWord" },
            { "{Sender}", "IronSoftware" },
            { "{phone}", "+123 456789" },
            { "{email}", "sale@ironsoftware.com" },
            { "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
        };

        // Replace placeholders in the document with actual data
        foreach (var replacement in replacements)
        {
            doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
        }

        // Save the filled document
        doc.Save(outputPath);

        // Notify the user that the document has been saved successfully
        Console.WriteLine("Document filled and saved successfully.");
    }
}
Imports System
Imports System.Collections.Generic
Imports IronWord

Friend Class Program
	Shared Sub Main()
		' Set the license key for IronWord
		License.LicenseKey = "your key"

		' Define paths for the template and the output file
		Dim templatePath As String = "Template.docx"
		Dim outputPath As String = "FilledDocument.docx"

		' Create a new instance of the WordDocument class using the template path
		Dim doc As New WordDocument(templatePath)

		' Define a dictionary of placeholders and their replacements
		Dim replacements = New Dictionary(Of String, String) From {
			{"{Name}", "John Doe"},
			{"{Date}", DateTime.Now.ToString("MMMM d, yyyy")},
			{"{Address}", "123 Iron Street, Iron Software"},
			{"{product}", "IronWord"},
			{"{Sender}", "IronSoftware"},
			{"{phone}", "+123 456789"},
			{"{email}", "sale@ironsoftware.com"},
			{"{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy")}
		}

		' Replace placeholders in the document with actual data
		For Each replacement In replacements
			doc.Texts.ForEach(Function(x) x.Replace(replacement.Key, replacement.Value))
		Next replacement

		' Save the filled document
		doc.Save(outputPath)

		' Notify the user that the document has been saved successfully
		Console.WriteLine("Document filled and saved successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

説明

提供されているコードは、IronWord ライブラリを使用して Word 文書テンプレートに特定のデータを入力する方法を示しています。 簡潔な説明は次のとおりです。 1.ライセンスの設定: コードは、IronWord の機能を有効にするためのライセンス キーを設定することから始まります。 2.ファイル パス: Word テンプレート ( Template.docx ) と出力ファイル ( FilledDocument.docx ) のパスを指定します。 3.ドキュメント インスタンスの作成: テンプレート パス参照を使用してWordDocumentのインスタンスが作成されます。 4.置換を定義する: キーがテンプレート内のプレースホルダーを表し、値が挿入するデータを表す辞書が作成されます。 5.プレースホルダーの置き換え: 辞書を反復処理して、ドキュメント内の各プレースホルダーを対応するデータに置き換えます。 6.ドキュメントの保存: 最後に、更新されたドキュメントが指定された出力パスに保存されます。 7.完了メッセージ: ドキュメントが正常に入力され保存されたことを確認するメッセージが印刷されます。

Output

C#でWordテンプレートを使用してWord文書を生成する方法: 図7 - Word文書の出力

ステップ 5: 生成された Word 文書にテキスト効果を追加します。

IronWord では、下の表に示すように、さまざまなテキスト効果を追加することもできます。

次の例では、"Iron Software"という単語にテキスト効果を追加します。

using System;
using System.Collections.Generic;
using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Set the license key for IronWord
        License.LicenseKey = "your key";

        // Define paths for the template and the output file
        string templatePath = "Template.docx";
        string outputPath = "glowEffect.docx";

        // Create a new instance of the WordDocument class
        WordDocument doc = new WordDocument(templatePath);

        // Define a dictionary of placeholders and their replacements
        var replacements = new Dictionary<string, string>
        {
            { "{Name}", "John Doe" },
            { "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
            { "{Address}", "123 Iron Street, Iron Software" },
            { "{product}", "IronWord" },
            { "{Sender}", "Sale," },
            { "{phone}", "+123 456789" },
            { "{email}", "sale@ironsoftware.com" },
            { "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
        };

        // Replace placeholders in the document with actual data
        foreach (var replacement in replacements)
        {
            doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
        }

        // Create and configure text style methods with a glow effect
        TextStyle textStyle = new TextStyle
        {
            TextEffect = new TextEffect()
            {
                GlowEffect = new Glow()
                {
                    GlowColor = IronWord.Models.Color.Aqua,
                    GlowRadius = 10,
                },
            }
        };

        // Add styled text to the document
        doc.AddText(" IronSoftware").Style = textStyle;

        // Save the document with the glow effect
        doc.SaveAs(outputPath);

        // Notify the user that the document has been saved successfully
        Console.WriteLine("Styled document saved successfully.");
    }
}
using System;
using System.Collections.Generic;
using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Set the license key for IronWord
        License.LicenseKey = "your key";

        // Define paths for the template and the output file
        string templatePath = "Template.docx";
        string outputPath = "glowEffect.docx";

        // Create a new instance of the WordDocument class
        WordDocument doc = new WordDocument(templatePath);

        // Define a dictionary of placeholders and their replacements
        var replacements = new Dictionary<string, string>
        {
            { "{Name}", "John Doe" },
            { "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
            { "{Address}", "123 Iron Street, Iron Software" },
            { "{product}", "IronWord" },
            { "{Sender}", "Sale," },
            { "{phone}", "+123 456789" },
            { "{email}", "sale@ironsoftware.com" },
            { "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
        };

        // Replace placeholders in the document with actual data
        foreach (var replacement in replacements)
        {
            doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
        }

        // Create and configure text style methods with a glow effect
        TextStyle textStyle = new TextStyle
        {
            TextEffect = new TextEffect()
            {
                GlowEffect = new Glow()
                {
                    GlowColor = IronWord.Models.Color.Aqua,
                    GlowRadius = 10,
                },
            }
        };

        // Add styled text to the document
        doc.AddText(" IronSoftware").Style = textStyle;

        // Save the document with the glow effect
        doc.SaveAs(outputPath);

        // Notify the user that the document has been saved successfully
        Console.WriteLine("Styled document saved successfully.");
    }
}
Imports System
Imports System.Collections.Generic
Imports IronWord
Imports IronWord.Models

Friend Class Program
	Shared Sub Main()
		' Set the license key for IronWord
		License.LicenseKey = "your key"

		' Define paths for the template and the output file
		Dim templatePath As String = "Template.docx"
		Dim outputPath As String = "glowEffect.docx"

		' Create a new instance of the WordDocument class
		Dim doc As New WordDocument(templatePath)

		' Define a dictionary of placeholders and their replacements
		Dim replacements = New Dictionary(Of String, String) From {
			{"{Name}", "John Doe"},
			{"{Date}", DateTime.Now.ToString("MMMM d, yyyy")},
			{"{Address}", "123 Iron Street, Iron Software"},
			{"{product}", "IronWord"},
			{"{Sender}", "Sale,"},
			{"{phone}", "+123 456789"},
			{"{email}", "sale@ironsoftware.com"},
			{"{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy")}
		}

		' Replace placeholders in the document with actual data
		For Each replacement In replacements
			doc.Texts.ForEach(Function(x) x.Replace(replacement.Key, replacement.Value))
		Next replacement

		' Create and configure text style methods with a glow effect
		Dim textStyle As New TextStyle With {
			.TextEffect = New TextEffect() With {
				.GlowEffect = New Glow() With {
					.GlowColor = IronWord.Models.Color.Aqua,
					.GlowRadius = 10
				}
			}
		}

		' Add styled text to the document
		doc.AddText(" IronSoftware").Style = textStyle

		' Save the document with the glow effect
		doc.SaveAs(outputPath)

		' Notify the user that the document has been saved successfully
		Console.WriteLine("Styled document saved successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

説明

修正されたコードは、IronWord ライブラリを使用して Word 文書テンプレートに入力し、テキストにスタイルを設定し、変更された文書を保存する方法を示しています。 簡潔な説明は次のとおりです。

1.ライセンス設定: 機能を有効にするために IronWord ライセンス キーを設定します。 2.ファイル パス: テンプレート ( Template.docx ) と出力ファイル ( glowEffect.docx ) のパスを指定します。 3.ドキュメント インスタンスの作成: 指定されたテンプレート パスを使用してWordDocumentインスタンスを初期化します。 4.置換の定義: プレースホルダーとそれに対応する置換値の辞書を作成します。 5.プレースホルダーの置き換え: 辞書を反復処理して、ドキュメント内のプレースホルダーを実際のデータに置き換えます。 6.テキスト スタイルの設定: 色と半径を指定して、グロー効果のあるテキスト スタイルを定義します。 7.スタイル付きテキストの追加: 設定されたスタイルを持つテキストをドキュメントに追加します。 8.ドキュメントを保存: 適用されたテキスト スタイルを反映して、更新されたドキュメントを新しい名前 ( glowEffect.docx ) で保存します。 9.コンソール出力: スタイル設定されたドキュメントが保存されたことを確認するメッセージが出力されます。

Output

C#でWordテンプレートを使用してWord文書を生成する方法: 図8 - Word出力の例

IronWord ライセンス

IronWord. Once the data is entered, the license is delivered to the email ID provided. このライセンスは、以下のように、 IronWordライブラリを使用する前にコードの先頭に配置する必要があります。

License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here"
$vbLabelText   $csharpLabel

結論

IronWord には、テンプレートを使用して Word 文書を生成するいくつかの利点があります。 開発者が特定のデータをプログラムでテンプレートに入力できるようにすることで、ドキュメント作成の自動化を簡素化し、手動入力の必要性を減らします。 これにより、人為的エラーのリスクが最小限に抑えられ、効率と精度が向上します。 さらに、 IronWord はドキュメント間の一貫性を維持し、生成される各ファイルが同じ形式と構造に準拠していることを保証します。 反復的なタスクを自動化すると、時間とリソースが節約され、大量のドキュメントを迅速に作成するのに最適です。 IronWord は、頻繁または複雑なドキュメント生成を必要とするシナリオで生産性を向上させ、ワークフローを合理化します。

この記事で概説されている手順に従い、 IronWordで提供された例を活用することで、ドキュメント生成のニーズを効率的に管理し、ワークフローを合理化できます。

よくある質問

C#を使用してWordドキュメントテンプレートを埋める方法は?

C#でIronWordを活用してWordドキュメントテンプレートを埋めることができます。まずVisual Studioでプロジェクトを設定し、NuGetを通じてIronWordパッケージをインストールします。Wordテンプレートを作成し、IronWordを使用してデータを挿入し、埋め込みテンプレートを新しいドキュメントとして保存します。

.NET ライブラリを使用した Word テンプレートの自動化のメリットは何ですか?

IronWord のような .NET ライブラリを使用して Word テンプレートを自動化することで、手動入力を減らし、エラーを最小限に抑え、文書作成の一貫性を確保します。請求、請求書作成、手紙作成などの作業を効率的に処理できます。

プログラムでWordテンプレートを埋める際にテキスト効果を追加できますか?

はい、IronWord を使用すると、テンプレートをプログラムで埋める際に、Word ドキュメント内のテキストに光彩や影などのテキスト効果を追加できます。

Visual Studio プロジェクトで IronWord を設定する手順は何ですか?

Visual Studio プロジェクトで IronWord を設定するには、まず IronWord NuGet パッケージをインストールし、Word テンプレートを作成し、その後、IronWord のメソッドを使用してプログラムでドキュメントを埋めて保存します。

IronWordはどのようにドキュメント生成の一貫性を確保しますか?

IronWordは、複数のドキュメントで同じ形式を維持するWordテンプレートを使用することで、人為的エラーを減らし、一貫性を確保します。

Wordドキュメント生成を自動化する実用的なアプリケーションにはどのようなものがありますか?

IronWord を使用した Word ドキュメント生成の自動化は、レポート生成、請求書作成、契約管理、個人的な手紙作成といった様々なシナリオに適用できます。

IronWord を使用して異なるバージョンの Microsoft Word を処理することは可能ですか?

はい、IronWord はさまざまなバージョンの Microsoft Word と互換性があり、異なる環境間での文書のシームレスな取り扱いを可能にします。

Word ドキュメント管理に IronWord を使用し始めるために必要なものは何ですか?

IronWord を使用し始めるには、Visual Studio と最新の .NET Framework がインストールされていることを確認し、NuGet パッケージ マネージャーを通じて IronWord をプロジェクトに追加します。

Jordi Bardia
ソフトウェアエンジニア
Jordiは、最も得意な言語がPython、C#、C++であり、Iron Softwareでそのスキルを発揮していない時は、ゲームプログラミングをしています。製品テスト、製品開発、研究の責任を分担し、Jordiは継続的な製品改善において多大な価値を追加しています。この多様な経験は彼を挑戦させ続け、興味を持たせており、Iron Softwareで働くことの好きな側面の一つだと言います。Jordiはフロリダ州マイアミで育ち、フロリダ大学でコンピュータサイエンスと統計学を学びました。