DocX Modify Document

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

When you are working with word files, you will not be creating new documents all the time. Sometimes, you will also need to edit the existing documents. DocX provides an easy way to open the existing document and add changes to your document as needed.

Let's consider the following word document which we have created in the previous article.

image

Now we want to add some more content to this document as shown in the following example.

public static void Example1()
{
    using (var doc = DocX.Load(@"D:\my_word_document.docx"))
    {
        // Add a title
        var t = doc.InsertParagraph(0, "Load Document with File name", false);
        t.FontSize(15d);
        t.SpacingAfter(50d);
        t.Alignment = Alignment.center;

        // Insert a Paragraph into this document.
        var p = doc.InsertParagraph();

        // Append some text and add formatting.
        p.Append("A small paragraph was added.");

        doc.SaveAs(@"D:\updated_word_document.docx");
    }
}

In the above example, you will see that we have called the SaveAs() method which saves the changes to the new file.

When you execute the above example, you will see that the new word document is created that contains the following data.

image

If you want to save the changes to the same file, you can just call the Save() method as shown below.

public static void Example2()
{
    using (var doc = DocX.Load(@"D:\my_word_document.docx"))
    {
        // Add a title
        var t = doc.InsertParagraph(0, "Load Document with File name", false);
        t.FontSize(15d);
        t.SpacingAfter(50d);
        t.Alignment = Alignment.center;

        // Insert a Paragraph into this document.
        var p = doc.InsertParagraph();

        // Append some text and add formatting.
        p.Append("A small paragraph was added.");

        doc.Save();
    }
}

Now when you execute the above example, you will see that the new word document is created that contains the following data.

image

Got any DocX Question?