Replace Text in Word with Table in C#

This topic is just another request from one of our users on Spire.Doc Forum. In order to let more people know about this function, we’re going to present the whole procedure through a sample demo in the article. Additionally, we would like to remind you that we offer free customized demo for both pay users and test users.

As a professional .NET Word component, Spire.Doc enables developers to replace specified paragraph with a newly created table or an existing table. In this example, the paragraph 3 in main body of the sample word file will be replaced by a newly-built table.

Test file:

Replace Text in Word with Table in C#

Code snippets for replacing text with table:

Step 1: Create a new word document and load the test file.

Document doc = new Document();
doc.LoadFromFile(@"..\..\test.docx");

Step 2: Return TextSection by finding the key text string "classical antiquity science".

Section section = doc.Sections[0];     
TextSelection selection = doc.FindString("classical antiquity science", true, true);

Step 3: Return TextRange from TextSection, then get OwnerParagraph through TextRange.

TextRange range = selection.GetAsOneRange();
Paragraph paragraph = range.OwnerParagraph;

Step 4: Return the zero-based index of the specified paragraph.

Body body = paragraph.OwnerTextBody;
int index = body.ChildObjects.IndexOf(paragraph);

Step 5: Create a new table.

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

Step 6: Remove the paragraph and insert table into the collection at the specified index.

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

Step 7: Save and launch the file.

doc.SaveToFile("result.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("result.doc");

Result:

Replace Text in Word with Table in C#

Full C# code:

         static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile(@"..\..\test.docx");
            Section section = doc.Sections[0];
            TextSelection selection = doc.FindString("classical antiquity science", 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.doc", FileFormat.Doc);
            System.Diagnostics.Process.Start("result.doc");

        }