0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#コードを使用してWord文書内のコンテンツコントロールを変更する

0
Posted at

Word文書では、コンテンツコントロールを使用することで、文書内のコンテンツを動的に更新・編集でき、より柔軟な編集・管理が可能になります。コンテンツコントロールを活用すれば、文書全体の構成を変更することなく、特定の部分のコンテンツを簡単に追加、削除、または変更できます。この記事では、C#を使用してWord文書内のコンテンツコントロールを変更する方法を紹介します。

.NET プロジェクトの準備

まず、.NETプロジェクトでWord文書を操作するために、必要なDLLファイルを参照として追加します。DLLファイルは、こちらからダウンロードするか、NuGetを使用してインストールできます。

PM> Install-Package Spire.Doc

C#を使用して本文内のコンテンツコントロールを変更する

Word文書では、本文内のコンテンツコントロールを StructureDocumentTag オブジェクトとして扱います。セクションの Section.Body に含まれる子オブジェクトを順に確認し、StructureDocumentTag 型のオブジェクトを見つけることで、対象のコンテンツコントロールを変更できます。

具体的な手順は以下のとおりです。

  • Document オブジェクトを作成します
  • Document.LoadFromFile() メソッドを使用して文書を読み込みます
  • Section.Body を使用して、文書内のセクション本文にアクセスします
  • Body.ChildObjects コレクションを反復処理し、StructureDocumentTag 型のオブジェクトを検索します
  • StructureDocumentTag.ChildObjects コレクションにアクセスし、子オブジェクトの種類に応じて必要な変更を行います
  • Document.SaveToFile() メソッドを使用して文書を保存します

完全なサンプルコードは以下のとおりです。

using Spire.Doc;
using Spire.Doc.Documents;
using System.Collections.Generic;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Documentオブジェクトを作成
            Document doc = new Document();

            // ファイルから文書を読み込む
            doc.LoadFromFile("Sample1.docx");

            // 文書の本文を取得
            Body body = doc.Sections[0].Body;

            // 段落とテーブル用のリストを作成
            List<Paragraph> paragraphs = new List<Paragraph>();
            List<Table> tables = new List<Table>();
            for (int i = 0; i < body.ChildObjects.Count; i++)
            {
                // 文書オブジェクトを取得
                DocumentObject documentObject = body.ChildObjects[i];

                // StructureDocumentTagオブジェクトかどうかを確認
                if (documentObject.DocumentObjectType == DocumentObjectType.StructureDocumentTag)
                {
                    StructureDocumentTag structureDocumentTag = (StructureDocumentTag)documentObject;

                    // タグまたはエイリアスが「c1」であるかを確認
                    if (structureDocumentTag.SDTProperties.Tag == "c1" || structureDocumentTag.SDTProperties.Alias == "c1")
                    {
                        for (int j = 0; j < structureDocumentTag.ChildObjects.Count; j++)
                        {
                            // 段落オブジェクトの場合
                            if (structureDocumentTag.ChildObjects[j].DocumentObjectType == DocumentObjectType.Paragraph)
                            {
                                Paragraph paragraph = (Paragraph)structureDocumentTag.ChildObjects[j];
                                paragraphs.Add(paragraph);
                            }

                            // テーブルオブジェクトの場合
                            if (structureDocumentTag.ChildObjects[j].DocumentObjectType == DocumentObjectType.Table)
                            {
                                Table table = (Table)structureDocumentTag.ChildObjects[j];
                                tables.Add(table);
                            }
                        }
                    }
                }
            }

            // 最初の段落のテキストを変更
            paragraphs[0].Text = ".NETライブラリを使用すると、Microsoft OfficeをインストールせずにWord文書を操作できます。";

            // 最初のテーブルのセル数をリセット
            tables[0].ResetCells(5, 4);

            // 変更した文書をファイルに保存
            doc.SaveToFile("ModifyBodyContentControls.docx", FileFormat.Docx2016);

            // 文書リソースを解放
            doc.Dispose();
        }
    }
}

C#を使用して段落内のコンテンツコントロールを変更する

Word文書では、段落内のコンテンツコントロールは StructureDocumentTagInline オブジェクトとして扱われます。これらを変更するには、Paragraph.ChildObjects コレクション内の子オブジェクトを順に確認し、StructureDocumentTagInline 型のオブジェクトを見つけて、必要な変更を行います。

具体的な手順は以下のとおりです。

  • Document オブジェクトを作成します
  • Document.LoadFromFile() メソッドを使用して文書を読み込みます
  • Section.Body を使用して、文書内のセクション本文にアクセスします
  • Body.Paragraphs[0] を使用して、本文の最初の段落を取得します
  • Paragraph.ChildObjects コレクションを反復処理し、StructureDocumentTagInline 型のオブジェクトを検索します
  • StructureDocumentTagInline.ChildObjects コレクションにアクセスし、子オブジェクトの種類に応じて必要な変更を行います
  • Document.SaveToFile() メソッドを使用して文書を保存します

完全なサンプルコードは以下のとおりです。

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Collections.Generic;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 新しいDocumentオブジェクトを作成
            Document doc = new Document();

            // ファイルから文書を読み込む
            doc.LoadFromFile("Sample2.docx");

            // 文書の本文を取得
            Body body = doc.Sections[0].Body;

            // 本文の最初の段落を取得
            Paragraph paragraph = body.Paragraphs[0];

            // 段落内の子オブジェクトを順に確認
            for (int i = 0; i < paragraph.ChildObjects.Count; i++)
            {
                // 子オブジェクトがStructureDocumentTagInlineかどうかを確認
                if (paragraph.ChildObjects[i].DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                {
                    // 子オブジェクトをStructureDocumentTagInline型に変換
                    StructureDocumentTagInline structureDocumentTagInline = (StructureDocumentTagInline)paragraph.ChildObjects[i];

                    // TagまたはAliasプロパティが「text1」かどうかを確認
                    if (structureDocumentTagInline.SDTProperties.Tag == "text1" || structureDocumentTagInline.SDTProperties.Alias == "text1")
                    {
                        // StructureDocumentTagInlineオブジェクト内の子オブジェクトを順に確認
                        for (int j = 0; j < structureDocumentTagInline.ChildObjects.Count; j++)
                        {
                            // 子オブジェクトがTextRangeオブジェクトかどうかを確認
                            if (structureDocumentTagInline.ChildObjects[j].DocumentObjectType == DocumentObjectType.TextRange)
                            {
                                // 子オブジェクトをTextRange型に変換
                                TextRange range = (TextRange)structureDocumentTagInline.ChildObjects[j];

                                // 指定したテキストに置き換える
                                range.Text = "97-2003/2007/2010/2013/2016/2019";
                            }
                        }
                    }

                    // TagまたはAliasプロパティが「logo1」かどうかを確認
                    if (structureDocumentTagInline.SDTProperties.Tag == "logo1" || structureDocumentTagInline.SDTProperties.Alias == "logo1")
                    {
                        // StructureDocumentTagInlineオブジェクト内の子オブジェクトを順に確認
                        for (int j = 0; j < structureDocumentTagInline.ChildObjects.Count; j++)
                        {
                            // 子オブジェクトが画像かどうかを確認
                            if (structureDocumentTagInline.ChildObjects[j].DocumentObjectType == DocumentObjectType.Picture)
                            {
                                // 子オブジェクトをDocPicture型に変換
                                DocPicture docPicture = (DocPicture)structureDocumentTagInline.ChildObjects[j];

                                // 指定した画像を読み込む
                                docPicture.LoadImage("Doc-NET.png");

                                // 画像の幅と高さを設定
                                docPicture.Width = 100;
                                docPicture.Height = 100;
                            }
                        }
                    }
                }
            }

            // 変更した文書を新しいファイルに保存
            doc.SaveToFile("ModifiedContentControlsInParagraph.docx", FileFormat.Docx2016);

            // Documentオブジェクトのリソースを解放
            doc.Dispose();
        }
    }
}

C#を使用して表の行を囲むコンテンツコントロールを変更する

Word文書では、表の行を囲むコンテンツコントロールは StructureDocumentTagRow オブジェクトとして扱われます。これを変更するには、Table.ChildObjects コレクション内の子オブジェクトを順に確認し、StructureDocumentTagRow 型のオブジェクトを検索して、必要な変更を行います。

具体的な手順は以下のとおりです。

  • Document オブジェクトを作成します
  • Document.LoadFromFile() メソッドを使用して文書を読み込みます
  • Section.Body を使用して、セクションの本文にアクセスします
  • Body.Tables[0] を使用して、本文内の最初の表を取得します
  • Table.ChildObjects コレクションを反復処理し、StructureDocumentTagRow 型のオブジェクトを検索します
  • StructureDocumentTagRow.Cells にアクセスし、各セルの内容に必要な変更を加えます
  • Document.SaveToFile() メソッドを使用して文書を保存します

完全なサンプルコードは以下のとおりです。

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 新しいDocumentオブジェクトを作成
            Document doc = new Document();

            // ファイルから文書を読み込む
            doc.LoadFromFile("Sample3.docx");

            // 文書の本文を取得
            Body body = doc.Sections[0].Body;

            // 最初の表を取得
            Table table = (Table)body.Tables[0];

            // 表内の子オブジェクトを順に確認
            for (int i = 0; i < table.ChildObjects.Count; i++)
            {
                // 子オブジェクトがStructureDocumentTagRow型かどうかを確認
                if (table.ChildObjects[i].DocumentObjectType == DocumentObjectType.StructureDocumentTagRow)
                {
                    // 子オブジェクトをStructureDocumentTagRow型に変換
                    StructureDocumentTagRow structureDocumentTagRow = (StructureDocumentTagRow)table.ChildObjects[i];

                    // TagまたはAliasプロパティが「row1」かどうかを確認
                    if (structureDocumentTagRow.SDTProperties.Tag == "row1" || structureDocumentTagRow.SDTProperties.Alias == "row1")
                    {
                        // セル内の段落をクリア
                        structureDocumentTagRow.Cells[0].Paragraphs.Clear();

                        // セルに段落を追加し、テキストを設定
                        TextRange textRange = structureDocumentTagRow.Cells[0].AddParagraph().AppendText("Arts");
                        textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                    }
                }
            }

            // 変更した文書をファイルに保存
            doc.SaveToFile("ModifiedTableRowContentControl.docx", FileFormat.Docx2016);

            // 文書のリソースを解放
            doc.Dispose();
        }
    }
}

C#を使用して表のセルを囲むコンテンツコントロールを変更する

Word文書では、表のセル内にあるコンテンツコントロールは StructureDocumentTagCell オブジェクトとして扱われます。TableRow.ChildObjects コレクション内の子オブジェクトを順に確認し、StructureDocumentTagCell 型のオブジェクトを見つけて、必要な操作を行います。

具体的な手順は以下のとおりです。

  • Document オブジェクトを作成します
  • Document.LoadFromFile() メソッドを使用して文書を読み込みます
  • Section.Body を使用して、セクションの本文にアクセスします
  • Body.Tables[0] を使用して、本文内の最初の表を取得します
  • Table.Rows コレクションを反復処理し、各 TableRow オブジェクトにアクセスします
  • TableRow.ChildObjects コレクション内の子オブジェクトを順に確認し、StructureDocumentTagCell 型のオブジェクトを検索します
  • StructureDocumentTagCell のコンテンツコントロールセルに含まれる段落コレクションにアクセスし、内容に必要な変更を加えます
  • Document.SaveToFile() メソッドを使用して文書を保存します

完全なサンプルコードは以下のとおりです。

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
             // 新しいDocumentオブジェクトを作成
            Document doc = new Document();

            // ファイルから文書を読み込む
            doc.LoadFromFile("Sample4.docx");

            // 文書の本文を取得
            Body body = doc.Sections[0].Body;

            // 文書内の最初の表を取得
            Table table = (Table)body.Tables[0];

            // 表の各行を順に確認
            for (int i = 0; i < table.Rows.Count; i++)
            {
                // 各行の子オブジェクトを順に確認
                for (int j = 0; j < table.Rows[i].ChildObjects.Count; j++)
                {
                    // 子オブジェクトがStructureDocumentTagCellかどうかを確認
                    if (table.Rows[i].ChildObjects[j].DocumentObjectType == DocumentObjectType.StructureDocumentTagCell)
                    {
                        // 子オブジェクトをStructureDocumentTagCell型に変換
                        StructureDocumentTagCell structureDocumentTagCell = (StructureDocumentTagCell)table.Rows[i].ChildObjects[j];

                        // TagまたはAliasプロパティが「cell1」かどうかを確認
                        if (structureDocumentTagCell.SDTProperties.Tag == "cell1" || structureDocumentTagCell.SDTProperties.Alias == "cell1")
                        {
                            // セル内の段落をクリア
                            structureDocumentTagCell.Paragraphs.Clear();

                            // 新しい段落を追加し、テキストを挿入
                            TextRange textRange = structureDocumentTagCell.AddParagraph().AppendText("92");
                            textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                        }
                    }
                }
            }

            // 変更した文書を新しいファイルに保存
            doc.SaveToFile("ModifiedTableCellContentControl.docx", FileFormat.Docx2016);

            // Documentオブジェクトを破棄
            doc.Dispose();
        }
    }
}

C#を使用して表のセル内にあるコンテンツコントロールを変更する

この例では、表のセル内の段落に含まれるコンテンツコントロールを変更する方法を紹介します。まず、TableCell.Paragraphs を使用してセル内の段落コレクションにアクセスします。次に、各段落の Paragraph.ChildObjects コレクションを反復処理し、StructureDocumentTagInline 型のオブジェクトを検索して、必要な変更を行います。

具体的な手順は以下のとおりです。

  • Document オブジェクトを作成します
  • Document.LoadFromFile() メソッドを使用して文書を読み込みます
  • Section.Body を使用して、セクションの本文にアクセスします
  • Body.Tables[0] を使用して、本文内の最初の表を取得します
  • Table.Rows コレクションを反復処理し、各 TableRow オブジェクトにアクセスします
  • TableRow.Cells コレクションを反復処理し、各 TableCell オブジェクトにアクセスします
  • TableCell.Paragraphs コレクションを反復処理し、各 Paragraph オブジェクトにアクセスします
  • Paragraph.ChildObjects コレクション内の子オブジェクトを確認し、StructureDocumentTagInline 型のオブジェクトを検索します
  • StructureDocumentTagInline オブジェクトの ChildObjects コレクションにアクセスし、子オブジェクトの種類に応じて必要な変更を行います
  • Document.SaveToFile() メソッドを使用して文書を保存します

完全なサンプルコードは以下のとおりです。

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 新しいDocumentオブジェクトを作成
            Document doc = new Document();

            // ファイルから文書を読み込む
            doc.LoadFromFile("Sample5.docx");

            // 文書の本文を取得
            Body body = doc.Sections[0].Body;

            // 最初の表を取得
            Table table = (Table)body.Tables[0];

            // 表の各行を順に確認
            for (int r = 0; r < table.Rows.Count; r++)
            {
                // 表の各行に含まれるセルを順に確認
                for (int c = 0; c < table.Rows[r].Cells.Count; c++)
                {
                    // セル内の段落を順に確認
                    for (int p = 0; p < table.Rows[r].Cells[c].Paragraphs.Count; p++)
                    {
                        // 段落オブジェクトを取得
                        Paragraph paragraph = table.Rows[r].Cells[c].Paragraphs[p];

                        // 段落内の子オブジェクトを順に確認
                        for (int i = 0; i < paragraph.ChildObjects.Count; i++)
                        {
                            // 子オブジェクトがStructureDocumentTagInline型かどうかを確認
                            if (paragraph.ChildObjects[i].DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                            {
                                // StructureDocumentTagInlineオブジェクトに変換
                                StructureDocumentTagInline structureDocumentTagInline = (StructureDocumentTagInline)paragraph.ChildObjects[i];

                                // TagまたはAliasプロパティが「test1」かどうかを確認
                                if (structureDocumentTagInline.SDTProperties.Tag == "test1" || structureDocumentTagInline.SDTProperties.Alias == "test1")
                                {
                                    // StructureDocumentTagInline内の子オブジェクトを順に確認
                                    for (int j = 0; j < structureDocumentTagInline.ChildObjects.Count; j++)
                                    {
                                        // 子オブジェクトがTextRange型かどうかを確認
                                        if (structureDocumentTagInline.ChildObjects[j].DocumentObjectType == DocumentObjectType.TextRange)
                                        {
                                            // TextRangeオブジェクトに変換
                                            TextRange textRange = (TextRange)structureDocumentTagInline.ChildObjects[j];

                                            // テキスト内容を設定
                                            textRange.Text = "89";

                                            // テキストの色を設定
                                            textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 変更した文書を新しいファイルに保存
            doc.SaveToFile("ModifiedContentControlInParagraphOfTableCell.docx", FileFormat.Docx2016);

            // Documentオブジェクトのリソースを解放
            doc.Dispose();
        }
    }
}

まとめ

Word文書のコンテンツコントロールは、本文、段落、表の行やセルなど、さまざまな場所に配置できます。C#を使用して対象のオブジェクトを取得し、テキストや画像、セルの内容などを変更することで、文書の特定の部分を効率的に編集できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?