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

Office Interopを使用せずにC#でワード文書を作成する方法

Microsoft Word 文書は、正式なビジネス レポートから個人的な手紙まで、さまざまな目的で広く使用されています。 C# では、開発者は多くの場合、プログラムによって Microsoft Word ドキュメントを生成する必要があります。 Windows アプリケーション開発者は、従来、Microsoft Office Interop を使用して、C# で Word ドキュメントを生成および作成してきました。

ただし、このアプローチは誰もが利用できるわけではなく、Microsoft Office インターフェースが利用できない OS や Linux マシンを使用している開発者もいます。 このような場合、開発者は、異なるプラットフォームで独立して動作できる他のライブラリを探す必要があります。 Word ファイルをプログラムで操作するための強力なライブラリの 1 つが、 Iron SoftwareIronWordです。

IronWord は、.NET アプリケーションで Word 文書を操作するための強力な機能を提供し、Linux ベースのさまざまなプラットフォームや Docker イメージ/コンテナーで実行できます。 直感的な C#、VB.NET Word、Docx Document API を備えた IronWord を使用すると、Word ドキュメント ファイルを作成、編集、エクスポートするために、Microsoft Office、Office オートメーション、または Word Interop をインストールする必要はありません。 IronWord は .NET 8、7、6、Framework、Core、Azure を完全にサポートしています。

この記事では、IronWord ライブラリを使用して C# で Word 文書を作成する方法について説明します。

C# で Office Interop を使用せずに Word 文書を作成する方法

  1. 新しいC#プロジェクトを作成します。
  2. IronWordライブラリをインストールします。
  3. IronWord ライブラリを使用して Word 文書を作成します。
  4. 既存のドキュメントにコンテンツを追加します。
  5. 作成したWord文書を保存します。
  6. 作成したWord文書を開いて表示します。

前提条件:

  1. Visual Studio: Visual Studio または他の C# 開発環境がインストールされていることを確認します。
  2. NuGetパッケージマネージャー: プロジェクトでNuGetを使用してパッケージを管理できることを確認してください。

ステップ 1: 新しい C# プロジェクトを作成する

新しい C# コンソール アプリケーションを作成するか、Word 文書を生成する既存のプロジェクトを使用します。

コンソールアプリケーション テンプレートを選択し、次へをクリックします。

C#でOffice相互運用性なしでWord文書を作成する方法: 図1 - 新しいプロジェクトを作成するためのコンソールアプリテンプレート

次のステップでは、ソリューションとプロジェクト名を提供できます。

C#でOffice相互運用性なしでWord文書を作成する方法: 図2 - ソリューションとプロジェクト名でプロジェクトを構成する

.NETバージョンを選択し、"作成"をクリックします。

C#でOffice相互運用性のないWord文書を作成する方法: 図3 - 正しい.NETバージョンでプロジェクトを作成する

ステップ 2: IronWord ライブラリのインストール

C# プロジェクトを開き、NuGet パッケージ マネージャー コンソールを使用してIronWordライブラリをインストールします。

Install-Package IronWord -Version 2024.1.2

NuGet パッケージは、以下に示すように、Visual Studio パッケージ マネージャーを使用してインストールすることもできます。

C#でOffice相互運用性なしでWord文書を作成する方法: 図4 - VSパッケージマネージャーを使用してIronWordをインストールする

ステップ3: IronWordライブラリを使用してWord文書を作成して保存する

まず、IronWord ライブラリを使用して Word 文書を作成する簡単な例から始めましょう。 次のコードは、"Hello, World!"というテキストを含む 1 つの段落を持つ基本的な Word 文書を作成する方法を示しています。

using IronWord;
using IronWord.Models;

// Create a text run instance with "Hello, World!" content
TextRun textRun = new TextRun("Hello, World!");

// Create a paragraph and add the text run to it
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Create a new Word document object with the paragraph
WordDocument doc = new WordDocument(paragraph);

// Save the document as a .docx file
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
using IronWord;
using IronWord.Models;

// Create a text run instance with "Hello, World!" content
TextRun textRun = new TextRun("Hello, World!");

// Create a paragraph and add the text run to it
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Create a new Word document object with the paragraph
WordDocument doc = new WordDocument(paragraph);

// Save the document as a .docx file
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
Imports IronWord
Imports IronWord.Models

' Create a text run instance with "Hello, World!" content
Private textRun As New TextRun("Hello, World!")

' Create a paragraph and add the text run to it
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)

' Create a new Word document object with the paragraph
Dim doc As New WordDocument(paragraph)

' Save the document as a .docx file
doc.SaveAs("example.docx") ' Saves the file to disk with the name example.docx
$vbLabelText   $csharpLabel

上記のコード例を実行すると、新しいドキュメント ファイルexample.docxが作成され、出力は次のようになります。

! C# で Office Interop を使用せずに Word 文書を作成する方法: 図 5 - 上記のコードで作成された Word 文書。

これは、IronWord を使用して Word 文書ファイルを生成する基本的な例です。 詳細については、ドキュメントをお読みください。

Word文書にスタイル付きの段落を追加する

IronWord を使用して簡単な Word 文書を作成する方法がわかったので、段落とスタイル付きテキストを追加してみましょう。

TextRun はスタイル データを取得して、テキストの視覚的な表現を強化することもできます。 テキストには取り消し線、太字、斜体、下線などのスタイルを設定できます。

以前作成したプログラムに以下のコードを修正して追加します。

using IronWord;
using IronWord.Models;

// Create text runs with different styles
TextRun textRun = new TextRun("Hello, World!"); // Simple string
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Configure and add italic text
TextRun introText = new TextRun("This is an example paragraph with italic and bold styling.");
TextStyle italicStyle = new TextStyle()
{
    IsItalic = true
};
TextRun italicText = new TextRun("Italic example sentence.", italicStyle);

// Configure and add bold text
TextStyle boldStyle = new TextStyle()
{
    IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);

// Add text runs to the paragraph
paragraph.AddTextRun(introText);
paragraph.AddTextRun(italicText);
paragraph.AddTextRun(boldText);

// Create and save the new Word document
WordDocument doc = new WordDocument(paragraph);
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
using IronWord;
using IronWord.Models;

// Create text runs with different styles
TextRun textRun = new TextRun("Hello, World!"); // Simple string
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Configure and add italic text
TextRun introText = new TextRun("This is an example paragraph with italic and bold styling.");
TextStyle italicStyle = new TextStyle()
{
    IsItalic = true
};
TextRun italicText = new TextRun("Italic example sentence.", italicStyle);

// Configure and add bold text
TextStyle boldStyle = new TextStyle()
{
    IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);

// Add text runs to the paragraph
paragraph.AddTextRun(introText);
paragraph.AddTextRun(italicText);
paragraph.AddTextRun(boldText);

// Create and save the new Word document
WordDocument doc = new WordDocument(paragraph);
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
Imports IronWord
Imports IronWord.Models

' Create text runs with different styles
Private textRun As New TextRun("Hello, World!") ' Simple string
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)

' Configure and add italic text
Dim introText As New TextRun("This is an example paragraph with italic and bold styling.")
Dim italicStyle As New TextStyle() With {.IsItalic = True}
Dim italicText As New TextRun("Italic example sentence.", italicStyle)

' Configure and add bold text
Dim boldStyle As New TextStyle() With {.IsBold = True}
Dim boldText As New TextRun("Bold example sentence.", boldStyle)

' Add text runs to the paragraph
paragraph.AddTextRun(introText)
paragraph.AddTextRun(italicText)
paragraph.AddTextRun(boldText)

' Create and save the new Word document
Dim doc As New WordDocument(paragraph)
doc.SaveAs("example.docx") ' Saves the file to disk with the name example.docx
$vbLabelText   $csharpLabel

Word文書に表を追加する

データを明確に表現するために、グリッドで表現することもできます。 データがグリッドとして配置されている場合、それはテーブルと呼ばれます。 IronWord を使用すると、次に示すように、Word 文書に表や画像を追加できます。

using IronWord;
using IronWord.Models;

// Create a table cell with sample text
TableCell cell = new TableCell();
TextRun textRun = new TextRun("Sample text");

// Add text run to the cell as a paragraph
cell.AddContent(new Paragraph(textRun));

// Configure cell border style
BorderStyle borderStyle = new BorderStyle
{
    BorderColor = new IronColor(IronSoftware.Drawing.Color.Black),
    BorderValue = IronWord.Models.Enums.BorderValues.Thick,
    BorderSize = 5
};

// Set table borders
TableBorders tableBorders = new TableBorders
{
    TopBorder = borderStyle,
    RightBorder = borderStyle,
    BottomBorder = borderStyle,
    LeftBorder = borderStyle
};
cell.Borders = tableBorders;

// Create a table row and add cells to it
TableRow row = new TableRow();
row.AddCell(cell); // Add the first cell
row.AddCell(cell); // Add the second cell, duplicating to mimic a row with two identical cells

// Create a table and add the row to the table
Table table = new Table();
table.AddRow(row);

// Create and save a Word document using the table
WordDocument doc = new WordDocument(table);
doc.SaveAs("Document.docx"); // Saves the file to disk with the name Document.docx
using IronWord;
using IronWord.Models;

// Create a table cell with sample text
TableCell cell = new TableCell();
TextRun textRun = new TextRun("Sample text");

// Add text run to the cell as a paragraph
cell.AddContent(new Paragraph(textRun));

// Configure cell border style
BorderStyle borderStyle = new BorderStyle
{
    BorderColor = new IronColor(IronSoftware.Drawing.Color.Black),
    BorderValue = IronWord.Models.Enums.BorderValues.Thick,
    BorderSize = 5
};

// Set table borders
TableBorders tableBorders = new TableBorders
{
    TopBorder = borderStyle,
    RightBorder = borderStyle,
    BottomBorder = borderStyle,
    LeftBorder = borderStyle
};
cell.Borders = tableBorders;

// Create a table row and add cells to it
TableRow row = new TableRow();
row.AddCell(cell); // Add the first cell
row.AddCell(cell); // Add the second cell, duplicating to mimic a row with two identical cells

// Create a table and add the row to the table
Table table = new Table();
table.AddRow(row);

// Create and save a Word document using the table
WordDocument doc = new WordDocument(table);
doc.SaveAs("Document.docx"); // Saves the file to disk with the name Document.docx
Imports IronWord
Imports IronWord.Models

' Create a table cell with sample text
Private cell As New TableCell()
Private textRun As New TextRun("Sample text")

' Add text run to the cell as a paragraph
cell.AddContent(New Paragraph(textRun))

' Configure cell border style
Dim borderStyle As New BorderStyle With {
	.BorderColor = New IronColor(IronSoftware.Drawing.Color.Black),
	.BorderValue = IronWord.Models.Enums.BorderValues.Thick,
	.BorderSize = 5
}

' Set table borders
Dim tableBorders As New TableBorders With {
	.TopBorder = borderStyle,
	.RightBorder = borderStyle,
	.BottomBorder = borderStyle,
	.LeftBorder = borderStyle
}
cell.Borders = tableBorders

' Create a table row and add cells to it
Dim row As New TableRow()
row.AddCell(cell) ' Add the first cell
row.AddCell(cell) ' Add the second cell, duplicating to mimic a row with two identical cells

' Create a table and add the row to the table
Dim table As New Table()
table.AddRow(row)

' Create and save a Word document using the table
Dim doc As New WordDocument(table)
doc.SaveAs("Document.docx") ' Saves the file to disk with the name Document.docx
$vbLabelText   $csharpLabel

上記の例では、境界線を使用して Word 文書に表を追加しました。

Word文書に画像を追加する

画像はドキュメントのプレゼンテーションを強化し、より多くの色と視覚的な魅力を加えることができます。

以下のコードに示すように、IronWord を使用してプログラムによって Word 文書に画像を追加できます。

using IronWord;
using IronWord.Models;

// Load a new document
WordDocument doc = new WordDocument();

// Configure and add image to the document
IronWord.Models.Image image = new IronWord.Models.Image("SalesChart.jpg")
{
    Width = 200, // Set image width in pixels
    Height = 200 // Set image height in pixels
};
Paragraph paragraph = new Paragraph();
paragraph.AddImage(image); // Add image to paragraph
doc.AddParagraph(paragraph); // Add paragraph to the document

// Save the document as a .docx file
doc.SaveAs("save_document.docx"); // Saves the file to disk with the name save_document.docx
using IronWord;
using IronWord.Models;

// Load a new document
WordDocument doc = new WordDocument();

// Configure and add image to the document
IronWord.Models.Image image = new IronWord.Models.Image("SalesChart.jpg")
{
    Width = 200, // Set image width in pixels
    Height = 200 // Set image height in pixels
};
Paragraph paragraph = new Paragraph();
paragraph.AddImage(image); // Add image to paragraph
doc.AddParagraph(paragraph); // Add paragraph to the document

// Save the document as a .docx file
doc.SaveAs("save_document.docx"); // Saves the file to disk with the name save_document.docx
Imports IronWord
Imports IronWord.Models

' Load a new document
Private doc As New WordDocument()

' Configure and add image to the document
Private image As New IronWord.Models.Image("SalesChart.jpg") With {
	.Width = 200,
	.Height = 200
}
Private paragraph As New Paragraph()
paragraph.AddImage(image) ' Add image to paragraph
doc.AddParagraph(paragraph) ' Add paragraph to the document

' Save the document as a .docx file
doc.SaveAs("save_document.docx") ' Saves the file to disk with the name save_document.docx
$vbLabelText   $csharpLabel

ここでは、 IronWord.Models.Imageを使用して、高さと幅が 200 ピクセルの画像を段落に追加しています。

ライセンス (無料トライアル利用可能)

IronWord を使用するにはライセンスが必要です。 Iron Softwareのウェブサイトからトライアルキーを入手してください。このキーはappsettings.jsonに配置する必要があります。

{
    "IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}

トライアルライセンスを取得するには、メールアドレスを提供してください。 メール ID を送信すると、キーがメールで届きます。

C#でOffice InteropなしでWord文書を作成する方法: 図6 - トライアルフォームの送信に成功した際のポップアップ

結論

IronWordライブラリを使用してC#でWord文書を作成すると、Microsoft Officeに依存せずに柔軟かつ効率的に文書を生成できます。シンプルな手紙から、表や画像を含む複雑なレポートまで、IronWordを使えばプログラムで作成できます。 この記事では、Word 文書の作成に関する包括的なチュートリアルを提供します。 IronWord を使用すると、Word 文書の作成を自動化できるため、C# アプリケーションの汎用性と生産性が向上します。

開発者が生成したWord文書と連携するPDFファイルの操作を探している場合は、IronPDFを見逃さないでください。これはIron Softwareが提供する別のC#ライブラリです。

よくある質問

Microsoft Office Interopを使わずにC#でWordドキュメントを作成するにはどうすればよいですか?

Microsoft Office Interopを使用せずにC#でWordドキュメントを作成するには、IronWORDライブラリを活用します。このライブラリを使用すれば、Microsoft Officeをインストールする必要なく、プログラム内でWordドキュメントを生成し、編集し、保存できます。

Microsoft Office InteropよりIronWORDを使用する利点は何ですか?

IronWORDはLinuxなどのMicrosoft Office Interopが使用できない非Windowsプラットフォームで動作する柔軟性を提供します。また、Microsoft Officeのインストール依存を排除し、開発プロセスを簡素化します。

IronWORDを使用してWordドキュメントの作成を始めるにはどうすればよいですか?

IronWORDを使用してWordドキュメントの作成を始めるには、まずC#プロジェクトでNuGetパッケージマネージャーを使用してIronWORDライブラリをインストールします。その後、IronWORD APIを使ってプログラム的にWordドキュメントを構築し操作します。

IronWORDは最新の.NETバージョンと互換性がありますか?

はい、IronWORDは.NET 8、7、6、Framework、Core、Azureなどのさまざまな.NETバージョンと互換性があります。これにより、現代的なC#アプリケーションに統合することができます。

IronWORDでWordドキュメントにスタイル付きテキストを追加するにはどうすればよいですか?

IronWORDは、TextRunTextStyleクラスを使用してスタイル付きテキストを追加できます。これらのクラスを使用して、Wordドキュメント内の特定のテキストセグメントに太字、イタリック、下線などのスタイルを適用することができます。

IronWORDを使用してWordドキュメントに表を含めることは可能ですか?

はい、IronWORDを使用してWordドキュメントに表を含めることができます。このライブラリでは、行やセルを持つ表を定義でき、境界線や他のスタイルで外観をカスタマイズできます。

IronWORDを使用してWordドキュメントに画像を挿入するにはどうすればよいですか?

IronWORDを使用してWordドキュメントに画像を挿入するには、IronWord.Models.Imageクラスを使って指定された寸法で画像を段落に埋め込むことができ、ドキュメントの視覚的なコンテンツを強化します。

IronWORDの評価用トライアルバージョンはありますか?

はい、Iron SoftwareはIronWORDの無料トライアルを提供しています。これを利用して、購入前にライブラリの機能と能力を評価することができます。

Iron Softwareは他にどのような文書操作ライブラリを提供していますか?

IronWORDに加えて、Iron SoftwareはPDFファイルを操作するためのIronPDFを提供しています。これらのライブラリが揃うことで、C#アプリケーションにおけるWordおよびPDF文書の取り扱いに対する包括的なソリューションを提供します。

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