How to replace text with table in a word document in C#

2014-08-28 01:30:27 Written by  support iceblue
Rate this item
(0 votes)

Spire.Doc has a powerful function of processing word table such as create and remove word table, set the table column width, style and so on. Spire.Doc also supports to add the table in the middle of the word document. This article will show you how to replace text with table by finding the key text in the word document.

Download and install Spire.Doc for .NET and then add Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll". Here comes to the details of how to finding the text and then replace it with table in C#.

Check the original word document at first:

Replace text with table in a word document in C#

Step 1: Create a new document and load from file.

Document doc = new Document();
doc.LoadFromFile("sample.docx");

Step 2: Find the place where you want to replace with table.

Section section = doc.Sections[0];
//"Fortune" as a "key text"
TextSelection selection = doc.FindString("Fortune", true, true);
TextRange range = selection.GetAsOneRange();
Paragraph paragraph = range.OwnerParagraph;
Body body = paragraph.OwnerTextBody;
int index = body.ChildObjects.IndexOf(paragraph);

Step 3: Add a table and set its style.

Table table = section.AddTable(true);
table.ResetCells(3,3);

Step 4: Remove the paragraph and insert the table.

body.ChildObjects.Remove(paragraph);
body.ChildObjects.Insert(index, table);

Step 5: Save the document to file.

doc.SaveToFile("Result.docx", FileFormat.Docx);

Effective screenshot of add a table in the middle of the word document by replacing the text.

Replace text with table in a word document in C#

Full codes:

namespace replaceTextwithTable
{
    class Program
    {
        static void Main(string[] args)
        {

            Document doc = new Document();
            doc.LoadFromFile("sample.docx");
            Section section = doc.Sections[0];
            TextSelection selection = doc.FindString("Fortune", true, true);
            TextRange range = selection.GetAsOneRange();
            Paragraph paragraph = range.OwnerParagraph;
            Body body = paragraph.OwnerTextBody;
            int index = body.ChildObjects.IndexOf(paragraph);
            Table table = section.AddTable(true);
            table.ResetCells(3,3);
            body.ChildObjects.Remove(paragraph);
             body.ChildObjects.Insert(index, table);
            doc.SaveToFile("Result.docx", FileFormat.Docx);
        }
    }
}

Additional Info

  • tutorial_title: Replace text with table in a word document
Last modified on Friday, 03 September 2021 03:52