C#でワードテンプレートを使用してワード文書を生成する方法
現代のアプリケーションでは、請求書、納品書、手紙などのさまざまな目的で Word 文書を即座に生成することが重要です。Microsoft Word テンプレート ドキュメント機能は、一貫性と効率性を確保するための強力な方法を提供します。 ただし、これらのテンプレートに手動で入力すると時間がかかり、エラーが発生しやすくなります。 ここで、 Iron SoftwareのIronWordが登場します。これは、Word テンプレートにデータを入力するプロセスをプログラムで自動化するように設計された強力な .NET ライブラリです。 この記事では、 IronWordを使用して Word 文書テンプレートに入力する方法を説明し、そのプロセスを示す実際の例を示します。
C#でWordテンプレートを使用してWord文書を生成する方法
- Microsoft Visual Studio で新しいプロジェクトを作成します。
- NuGet パッケージ マネージャーを使用してIronWordをインストールします。
- Word テンプレート文書を作成します。
- Word 文書にデータを挿入し、新しいファイルとして保存します。
- 生成された 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 Frameworkがインストールされている。
ステップ 1: Microsoft Visual Studio で新しいプロジェクトを作成します
では、新しい Visual Studio プロジェクトを作成することから始めましょう。

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

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

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

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

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

ステップ 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
説明
修正されたコードは、IronWord ライブラリを使用して Word 文書テンプレートに入力し、テキストにスタイルを設定し、変更された文書を保存する方法を示しています。 簡潔な説明は次のとおりです。
1.ライセンス設定: IronWordのライセンスキーを設定して、機能を有効にします。
2.ファイルパス:テンプレート(glowEffect.docx)のパスを指定します。
3.ドキュメントインスタンスの作成:指定されたテンプレートパスを使用して WordDocument インスタンスを初期化します。
4.置換の定義:プレースホルダーとそれに対応する置換値の辞書を作成します。
5.プレースホルダーの置換:ディクショナリを反復処理し、ドキュメント内のプレースホルダーを実際のデータに置き換えます。
6.テキストスタイルの設定:グロー効果のあるテキストスタイルを定義し、色と半径を指定します。
7.スタイル付きテキストの追加:設定したスタイルでテキストをドキュメントに追加します。
8.ドキュメントの保存:適用されたテキストスタイルを反映した新しい名前(glowEffect.docx)で更新されたドキュメントを保存します。
9.コンソール出力:スタイルが適用されたドキュメントが保存されたことを確認するメッセージが表示されます。
出力

IronWord ライセンス
IronWordの無料トライアルライセンスを取得してください。 データを入力すると、ライセンスが指定されたメールIDに送付されます。 このライセンスは、以下のように、 IronWordライブラリを使用する前にコードの先頭に配置する必要があります。
License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here"
結論
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 をプロジェクトに追加します。



