IRONWORDの使用

C#でフォーマットを保持してWordドキュメントを読み取る方法

更新済み 2月 22, 2024
共有:

Microsoft Word文書には、フォントやスタイル、視覚的にアピールするさまざまな要素など、豊富な書式が含まれていることがよくあります。 IronWord (アイアンワード) は、次のような強力なライブラリです。 アイアンソフトウェア C# (シーシャープ)とVB.NETの直感的なWordとDocxドキュメントAPIを持っています。 Microsoft OfficeやWord Interopをインストールしなくても、Word文書の作成、編集、エクスポートが可能です。 IronWordは.NET 8、7、6、フレームワーク、コア、Azureを完全にサポートしています。 つまり、このライブラリーは、マシンにインストールされたWordを必要とせず、独立してファイルを読み込む。 C#(シーシャープ)を使っていて、Word文書を書式を保持したまま読む必要がある場合、このチュートリアルでは IronWord ライブラリ。

(シーシャープで)ワード文書をフォーマットして読む方法

  1. IronWord (アイアンワード) ライブラリをインストールし、Word文書を読み込む。

  2. IronWord (アイアンワード) ライブラリの WordDocument クラスを使って入力ワード文書 'sample.docx' をロードする。

  3. 読み込んだWord文書を使って、書式付きの段落を読む。

  4. 抽出されたデータをフォーマット情報とともにコンソール出力に表示する。

前提条件

  1. Visual Studio: Visual Studio または他の C# 開発環境がインストールされていることを確認してください。

  2. NuGetパッケージマネージャー: プロジェクト内のパッケージ管理にNuGetを使用できるようにしてください。

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

C#(シーシャープ)コンソールアプリケーションを新規に作成するか、既存のプロジェクトを使用してWord文書を読み込む。

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

C#(シーシャープ)でWord文書を書式付きで読む方法:図1 - C#(シーシャープ)プロジェクトの新規作成

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

C#(シーシャープ)でWord文書を書式付きで読む方法:図2 - 新規プロジェクトの設定

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

C#(シーシャープ)でWord文書を書式付きで読む方法:図3-必要な.NETバージョンタイプの選択

ステップ 2: IronWordライブラリのインストール (アイアンワード・ライブラリー)

C#(シーシャープ)プロジェクトを開き、NuGet Package Manager Consoleを使用してアイアンワードライブラリをインストールします:

Install-Package IronWord

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

C#(シーシャープ)でWord文書を書式付きで読む方法:図4 - NuGetパッケージマネージャによるIronWordのインストール

ステップ3:書式付きWord文書を読む

Wordファイルを読むには、まず新しい文書を作成し、以下のように内容を追加する必要がある。

C#(シーシャープ)でWord文書を書式付きで読む方法:図5 - 作成したサンプル文書

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

C#(シーシャープ)でWord文書を書式付きで読む方法:図6 - ファイルのプロパティはどのように見えるか

次に、以下のコード・スニペットをprogram.csファイルに追加する。

using IronWord;
class Program
{
    static void Main()
    {
        try
        {
            // Load existing docx
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract Formatting details
                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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract Formatting details
                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
			For Each paragraph In paragraphs
				Dim textRun = paragraph.FirstTextRun
				Dim text = textRun.Text ' read the text
				' Extract Formatting details
				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
VB   C#

上記のコードでは、IronWord ライブラリクラスのコンストラクタ WordDocument メソッドを使って Word ドキュメントを読み込んでいます。

出力

C#(シーシャープ)でWord文書を書式付きで読む方法:図7 - 先ほどのコードのコンソール出力

説明

  1. Word文書を開く:IronWord (アイアンワード)の WordDocument を使ってワード文書を読み込む。

  2. パラグラフとランを繰り返し処理する:ネストされたループを使用して、パラグラフとランを繰り返し処理する。 実行は、特定の書式を持つテキストの一部を表す。

  3. テキストとフォーマットの抽出:各実行からテキストコンテンツを抽出し、フォーマットプロパティをチェックします。 この例では、フォントサイズと太字書式を抽出する方法を示した。

  4. 例外を処理する:try-and-catchブロックは、あらゆる例外を処理し、それらを表示するために使用されます。

    読み込まれたファイルは文書の印刷に使用でき、スタイル・オブジェクトでフォントの色を変更することもできます。

Wordファイルから表を読み込む

Word文書から表を読み取ることもできる。 以下のコード・スニペットをプログラムに追加する。

using IronWord;
class Program
{
    static void Main()
    {
        try
        {
            // Load existing docx
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            // 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");
            var paragraphs = sampleDoc.Paragraphs;
            // 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")
			Dim paragraphs = sampleDoc.Paragraphs
			' 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
VB   C#

ここでは WordDocument クラスの get/set メソッド 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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract Formatting details
                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 formating of the text
            var style = new TextStyle()
            {
                FontFamily = "Caveat",
                FontSize = 72,
                TextColor = new IronColor(Color.Blue), // blue color
                IsBold = true,
                IsItalic = true,
                IsUnderline = true,
                IsSuperscript = false,
                IsStrikethrough = true,
                IsSubscript = false
            };
            paragraphs [1].FirstTextRun.Style = style;
            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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract Formatting details
                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 formating of the text
            var style = new TextStyle()
            {
                FontFamily = "Caveat",
                FontSize = 72,
                TextColor = new IronColor(Color.Blue), // blue color
                IsBold = true,
                IsItalic = true,
                IsUnderline = true,
                IsSuperscript = false,
                IsStrikethrough = true,
                IsSubscript = false
            };
            paragraphs [1].FirstTextRun.Style = style;
            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
			For Each paragraph In paragraphs
				Dim textRun = paragraph.FirstTextRun
				Dim text = textRun.Text ' read the text
				' Extract Formatting details
				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 formating of the text
			Dim style = New TextStyle() With {
				.FontFamily = "Caveat",
				.FontSize = 72,
				.TextColor = New IronColor(Color.Blue),
				.IsBold = True,
				.IsItalic = True,
				.IsUnderline = True,
				.IsSuperscript = False,
				.IsStrikethrough = True,
				.IsSubscript = False
			}
			paragraphs (1).FirstTextRun.Style = style
			sampleDoc.SaveAs("sample2.docx")
		Catch ex As Exception
			Console.WriteLine($"An error occurred: {ex.Message}")
		End Try
	End Sub
End Class
VB   C#

ここでは、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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract the formatting details
                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(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
            TextRun introText = new TextRun("This is an example newParagraph 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 text
            newParagraph.AddTextRun(introText);
            newParagraph.AddTextRun(italicText);
            newParagraph.AddTextRun(boldText);
            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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract the formatting details
                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(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
            TextRun introText = new TextRun("This is an example newParagraph 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 text
            newParagraph.AddTextRun(introText);
            newParagraph.AddTextRun(italicText);
            newParagraph.AddTextRun(boldText);
            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
			For Each paragraph In paragraphs
				Dim textRun = paragraph.FirstTextRun
				Dim text = textRun.Text ' read the text
				' Extract the formatting details
				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(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
			Dim introText As New TextRun("This is an example newParagraph 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 text
			newParagraph.AddTextRun(introText)
			newParagraph.AddTextRun(italicText)
			newParagraph.AddTextRun(boldText)
			sampleDoc.SaveAs("sample2.docx")
		Catch ex As Exception
			Console.WriteLine($"An error occurred: {ex.Message}")
		End Try
	End Sub
End Class
VB   C#

ここでは、スタイル情報を持つ新しいTextRunオブジェクトとParagraphオブジェクトを作成し、読み込んだWord文書に追加しています。

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

IronWord. このキーはappsettings.jsonに配置する必要があります。

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

試用ライセンスを取得するためにメールアドレスを提供してください。 電子メールIDを送信すると、キーが電子メールで配信されます。

C#(シーシャープ)でWord文書を書式付きで読む方法:図8 - 正常に送信されたトライアルフォーム

結論

IronWord は、C#(シーシャープ)で書式付きWord文書を読む便利な方法を提供します。 提供されたコードを、特定の要件や扱う文書の複雑さに応じて拡張してください。 このチュートリアルは、以下を統合するための出発点となります。 IronWord を C# (シーシャープ) アプリケーションに組み込んで Word 文書を処理します。

< 以前
Office Interopを使用せずにC#でWordドキュメントを作成する方法
次へ >
開発者向け3つのC#ワードライブラリ (更新リスト)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 4,489 View Licenses >