C#でフォーマットされたワード文書を読む方法
Microsoft Word ドキュメントは、フォント、スタイル、さまざまな要素などのリッチな書式設定を含むことが多く、それによって視覚的な魅力が増します。 IronWord は、Iron Software による強力なライブラリで、直感的な C# および VB.NET の Word や Docx ドキュメント API を備えています。 Microsoft Office や Word Interop をインストールする必要はなく、Word ドキュメントの作成、編集、エクスポートが可能です。 IronWord は .NET 8、7、6、Framework、Core、Azure を完全にサポートしています。 これは、ライブラリがマシンにインストールされた Word を必要とせず、ファイルを独立して読み取ることを意味します。 C# を使用していて、書式設定を保持しながら Word ドキュメントを読み取る必要がある場合、このチュートリアルでは IronWord ライブラリを使用してプロセスを案内します。
C# で書式設定を保持して Word ドキュメントを読む方法
- Word ドキュメントを読むために IronWord ライブラリをインストールします。
- IronWord ライブラリの
WordDocumentクラスを使用して、入力の Word ドキュメント 'sample.docx' を読み込みます。 - 読み込んだ Word ドキュメントを使用して、書式設定された段落を読み取ります。
- 抽出したデータを書式情報と共にコンソール出力に表示します。
前提条件
- Visual Studio: Visual Studio または他の C# 開発環境がインストールされていることを確認します。
- NuGet パッケージ マネージャー: プロジェクトでパッケージを管理できるように NuGet が使用できることを確認します。
ステップ 1: 新しい C# プロジェクトを作成する
Word ドキュメントを読みたい場合は、新しい C# コンソールアプリケーションを作成するか、既存のプロジェクトを利用します。
コンソールアプリケーション テンプレートを選択し、次へをクリックします。

'次へ' ボタンをクリックして、ソリューション名、プロジェクト名、コードのパスを指定します。

その後、希望する .NET バージョンを選択します。 ベスト プラクティスは常に最新のバージョンを選択することですが、プロジェクトに特定の要件がある場合は必要な .NET バージョンを使用してください。

ステップ 2: IronWord ライブラリのインストール
C# プロジェクトを開き、NuGet パッケージ マネージャー コンソールを使用して IronWord ライブラリをインストールします。
Install-Package IronWord
NuGet パッケージは、以下に示すように Visual Studio の NuGet パッケージ マネージャーを使用してインストールすることもできます。

ステップ 3: 書式設定を保持して Word ドキュメントを読み取る
Word ファイルを読み取るには、まず新しいドキュメントを作成し、次のようにいくつかのコンテンツを追加する必要があります。

ファイルをプロジェクトディレクトリに保存し、出力ディレクトリにコピーするようにファイルのプロパティを変更します。

以下のコードスニペットを program.cs ファイルに追加します。
using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through each paragraph in the Word document
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through each paragraph in the Word document
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}Imports Microsoft.VisualBasic
Imports IronWord
Friend Class Program
Shared Sub Main()
Try
' Load existing docx
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
' Iterate through each paragraph in the Word document
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' Read text content
' Extract Formatting details if available
If textRun.Style IsNot Nothing Then
Dim fontSize = textRun.Style.FontSize ' Font size
Dim isBold = textRun.Style.IsBold
Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
Else
' Print text without formatting details
Console.WriteLine($vbTab & "Text: {text}")
End If
Next paragraph
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Class上記のコードは、IronWord ライブラリの WordDocument コンストラクタメソッドを使用して Word ドキュメントを読み取ります。
出力

説明
- Word ドキュメントを開く: IronWord の
WordDocumentを使用して Word ドキュメントを読み込みます。 - 段落とランを反復処理する: 入れ子になったループを使って段落とランを反復処理します。 ランは特定の書式設定がされたテキスト部分を表します。
- テキストと書式設定の抽出: 各ランからテキストコンテンツを抽出し、書式プロパティを確認します。 この例では、フォントサイズと太字の書式設定を抽出する方法をデモンストレーションします。
- 例外処理: 例外を処理してそれを印刷するために、try-and-catch ブロックを使用します。
読み込まれたファイルは印刷ドキュメントに使用でき、スタイルオブジェクトでフォントカラーも変更できます。
Word ファイルからテーブルを読む
Word ドキュメントからテーブルを読むこともできます。 以下のコードスニペットをプログラムに追加します。
using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
// Read Tables
var tables = sampleDoc.Tables;
foreach (var table in tables)
{
var rows = table.Rows;
foreach (var row in rows)
{
foreach (var cell in row.Cells)
{
var contents = cell.Contents;
contents.ForEach(x => Console.WriteLine(x));
// Print cell contents
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
// Read Tables
var tables = sampleDoc.Tables;
foreach (var table in tables)
{
var rows = table.Rows;
foreach (var row in rows)
{
foreach (var cell in row.Cells)
{
var contents = cell.Contents;
contents.ForEach(x => Console.WriteLine(x));
// Print cell contents
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}Imports IronWord
Friend Class Program
Shared Sub Main()
Try
' Load existing docx
Dim sampleDoc = New WordDocument("sample.docx")
' Read Tables
Dim tables = sampleDoc.Tables
For Each table In tables
Dim rows = table.Rows
For Each row In rows
For Each cell In row.Cells
Dim contents = cell.Contents
contents.ForEach(Sub(x) Console.WriteLine(x))
' Print cell contents
Next cell
Next row
Next table
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Classここでは、WordDocument クラスの Tables プロパティを使用してドキュメント内のすべてのテーブルを取得し、それらを反復処理してコンテンツを印刷しています。
既存のテキストにスタイルを追加する
以下のコードスニペットに示すように、IronWord ライブラリを使用して既存の Word ドキュメントに新しいスタイル情報を追加できます。
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Change the formatting of the text
var style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].FirstTextRun.Style = style;
// Save the document with the new style applied
sampleDoc.SaveAs("sample2.docx");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Change the formatting of the text
var style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].FirstTextRun.Style = style;
// Save the document with the new style applied
sampleDoc.SaveAs("sample2.docx");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}Imports Microsoft.VisualBasic
Imports IronWord
Imports IronWord.Models
Friend Class Program
Shared Sub Main()
Try
' Load existing docx
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
' Iterate through paragraphs
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' Read text content
' Extract Formatting details if available
If textRun.Style IsNot Nothing Then
Dim fontSize = textRun.Style.FontSize ' Font size
Dim isBold = textRun.Style.IsBold
Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
Else
' Print text without formatting details
Console.WriteLine($vbTab & "Text: {text}")
End If
Next paragraph
' Change the formatting of the text
Dim style = New TextStyle() With {
.FontFamily = "Caveat",
.FontSize = 72,
.TextColor = New IronColor(System.Drawing.Color.Blue),
.IsBold = True,
.IsItalic = True,
.IsUnderline = True,
.IsSuperscript = False,
.IsStrikethrough = True,
.IsSubscript = False
}
paragraphs(1).FirstTextRun.Style = style
' Save the document with the new style applied
sampleDoc.SaveAs("sample2.docx")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Classここでは、TextStyle を作成し、それを既存の段落オブジェクトに追加しています。
Word ドキュメントに新しいスタイル付きコンテンツを追加する
以下のコードスニペットに示すように、ロードされた Word ドキュメントに新しいコンテンツを追加できます。
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load Word Document
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract the formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Add TextRun with Style to Paragraph
TextRun blueTextRun = new TextRun();
blueTextRun.Text = "Add text using IronWord";
blueTextRun.Style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].AddTextRun(blueTextRun);
// Add New Content to the Word file and save
Paragraph newParagraph = new Paragraph();
TextRun newTextRun = new TextRun("New Add Information");
newParagraph.AddTextRun(newTextRun);
// Configure the text with different styles
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);
TextStyle boldStyle = new TextStyle()
{
IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);
// Add the styled text to the paragraph
newParagraph.AddTextRun(introText);
newParagraph.AddTextRun(italicText);
newParagraph.AddTextRun(boldText);
// Save the modified document
sampleDoc.SaveAs("sample2.docx");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load Word Document
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract the formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Add TextRun with Style to Paragraph
TextRun blueTextRun = new TextRun();
blueTextRun.Text = "Add text using IronWord";
blueTextRun.Style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].AddTextRun(blueTextRun);
// Add New Content to the Word file and save
Paragraph newParagraph = new Paragraph();
TextRun newTextRun = new TextRun("New Add Information");
newParagraph.AddTextRun(newTextRun);
// Configure the text with different styles
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);
TextStyle boldStyle = new TextStyle()
{
IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);
// Add the styled text to the paragraph
newParagraph.AddTextRun(introText);
newParagraph.AddTextRun(italicText);
newParagraph.AddTextRun(boldText);
// Save the modified document
sampleDoc.SaveAs("sample2.docx");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}Imports Microsoft.VisualBasic
Imports IronWord
Imports IronWord.Models
Friend Class Program
Shared Sub Main()
Try
' Load Word Document
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
' Iterate through paragraphs
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' Read text content
' Extract the formatting details if available
If textRun.Style IsNot Nothing Then
Dim fontSize = textRun.Style.FontSize ' Font size
Dim isBold = textRun.Style.IsBold
Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
Else
' Print text without formatting details
Console.WriteLine($vbTab & "Text: {text}")
End If
Next paragraph
' Add TextRun with Style to Paragraph
Dim blueTextRun As New TextRun()
blueTextRun.Text = "Add text using IronWord"
blueTextRun.Style = New TextStyle() With {
.FontFamily = "Caveat",
.FontSize = 72,
.TextColor = New IronColor(System.Drawing.Color.Blue),
.IsBold = True,
.IsItalic = True,
.IsUnderline = True,
.IsSuperscript = False,
.IsStrikethrough = True,
.IsSubscript = False
}
paragraphs(1).AddTextRun(blueTextRun)
' Add New Content to the Word file and save
Dim newParagraph As New Paragraph()
Dim newTextRun As New TextRun("New Add Information")
newParagraph.AddTextRun(newTextRun)
' Configure the text with different styles
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)
Dim boldStyle As New TextStyle() With {.IsBold = True}
Dim boldText As New TextRun("Bold example sentence.", boldStyle)
' Add the styled text to the paragraph
newParagraph.AddTextRun(introText)
newParagraph.AddTextRun(italicText)
newParagraph.AddTextRun(boldText)
' Save the modified document
sampleDoc.SaveAs("sample2.docx")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Classここではスタイル情報を持つ新しい TextRun および Paragraph オブジェクトを作成し、それを読み込まれた Word ドキュメントに追加しています。
ライセンス (無料トライアル利用可能)
IronWord 無料トライアルライセンスキーを取得。 このキーは appsettings.json に配置する必要があります。
{
"IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}トライアルライセンスを取得するには、メールアドレスを提供してください。 メール ID を送信すると、キーがメールで届きます。

結論
IronWord は、C# で書式付きの Word ドキュメントを読むための便利な方法を提供します。 特定の要件や作業しているドキュメントの複雑さに基づいて、提供されたコードを拡張してください。 このチュートリアルは、C# アプリケーションに IronWord を統合して Word ドキュメントを処理する際の出発点として役立ちます。
よくある質問
C# で書式付きの Word ドキュメントをどのように読み取ることができますか?
C# で書式付きの Word ドキュメントを読み取るには、IronWord ライブラリを使用します。最初に、NuGet パッケージ マネージャーを介して IronWord をインストールします。WordDocument クラスを使用してドキュメントを読み込み、段落を反復してテキストと書式の詳細を抽出します。
C# プロジェクトを設定して Word ドキュメントを読み取るための手順は何ですか?
Word ドキュメントを読み取るための C# プロジェクトを設定するには、Visual Studio または別の C# 開発環境をインストールします。NuGet パッケージ マネージャーを使用してプロジェクトに IronWord を追加します。WordDocument クラスを使用して Word ドキュメントを読み込み、その内容にアクセスします。
C# で Word ドキュメントを読み取る際に、例外をどのように処理しますか?
IronWord を使用して C# で Word ドキュメントを読み取る際は、try-catch ブロックをドキュメント処理コードの周りに実装して例外を処理します。これにより、実行時エラーに対処し、堅牢なアプリケーション動作が保証されます。
C# で Word ドキュメントから表を読み取ることはできますか?
はい、C# で IronWord を使用して Word ドキュメントから表を読み取ることができます。WordDocument クラスの Tables プロパティを介して表にアクセスし、必要に応じて表データを反復します。
C# で Word ドキュメントのテキストスタイルをどのように変更しますか?
IronWord を使用して Word ドキュメントのテキストスタイルを変更するには、TextStyle オブジェクトを作成し、それを特定のテキストランまたは段落に適用します。これにより、フォント、サイズ、その他のスタイル属性をカスタマイズできます。
C# で Word ドキュメントに新しいコンテンツを追加することは可能ですか?
はい、C# で IronWord を使用して Word ドキュメントに新しいコンテンツを追加することができます。TextRun および Paragraph オブジェクトを作成して、ドキュメントに書式付きコンテンツを追加し、変更を保存する前におこないます。
C# で Word ドキュメントに対する変更をどのように保存しますか?
IronWord を使用して Word ドキュメントを編集した後、WordDocument インスタンスの Save メソッドを呼び出して変更を保存します。ファイルパスを指定して、適用された変更が反映された新しいドキュメントを作成します。
C# で Word ドキュメントを処理するために Microsoft Office がインストールされている必要がありますか?
いいえ、C# で IronWord を使用して Word ドキュメントを処理するために Microsoft Office をインストールする必要はありません。このライブラリは Microsoft Office とは独立して機能し、Word ファイルを直接操作できます。
どの .NET バージョンが Word 処理ライブラリに対応していますか?
IronWord は、.NET 8、7、6、Framework、Core、Azure など、さまざまな .NET バージョンに対応しています。これにより、さまざまなプロジェクトの要件と環境に対応します。
C# で Word 処理ライブラリのトライアルライセンスをどのように取得しますか?
IronWord のトライアルライセンスを取得するには、Iron Software のウェブサイトにアクセスしてメールアドレスを提供します。メールでトライアルライセンスキーが送信され、appsettings.jsonファイルに追加できます。








