C#: Edit Word Documents

2024-08-08 06:35:00 Written by  Administrator
Rate this item
(0 votes)

Editing a Word document is necessary when you want to improve readability, correct errors, refine formatting, maintain consistency, adapt content, facilitate collaboration, and optimize the document for any other purposes. Programmatically editing a Word document using C# can be a powerful approach to automate document processing and manipulation tasks.

In this article, you will learn how to edit a Word document using C# and the Spire.Doc for .NET library.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Modify Text in a Word Document in C#

Spire.Doc allows you to programmatically access specific sections and paragraphs in Word documents. To retrieve a particular section, use the Document.Sections[index] property. Then, to get a particular paragraph within that section, leverage the Section.Paragraphs[index] property. Finally, you can update the text content of the paragraph using the Paragraph.Text property.

The steps to modify text in a Word document using C# are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Get a specific paragraph through Section.Paragraphs[index] property.
  • Reset the text of the paragraph through Paragraph.Text property.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace ModifyText
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new document object
            Document document = new Document();

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get a specific section
            Section section = document.Sections[0];

            // Get a specific paragraph
            Paragraph paragraph = section.Paragraphs[0];

            // Modify the text of the paragraph 
            paragraph.Text = "Updated Title";

            // Save the document to a different Word file
            document.SaveToFile("ModifyText.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

C#: Edit Word Documents

Change Formatting of Text in a Word Document in C#

To change the text formatting within a paragraph, first obtain the paragraph object, then iterate through its child objects to locate the individual text ranges. For each text range, you can reset the formatting using the CharacterFormat property of the TextRange.

The steps to change text formatting in a Word document are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Get a specific paragraph through Section.Paragraphs[index] property.
  • Iterate through the child objects in the paragraph.
    • Determine if a child object is a text range.
    • Get a specific text range.
    • Reset the text formatting through TextRange.CharacterFormat property.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

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

            // Create a new document object
            Document document = new Document();

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get a specific section
            Section section = document.Sections[0];

            // Get a specific paragraph
            Paragraph paragraph = section.Paragraphs[2];

            // Iterate through the child objects in the paragraph
            for (int i = 0; i < paragraph.ChildObjects.Count; i++)
            {

                // Determine if a child object is text range
                if (paragraph.ChildObjects[i] is TextRange)
                {
                    // Get a specific text range
                    TextRange textRange = (TextRange)paragraph.ChildObjects[i];

                    // Reset font name for it
                    textRange.CharacterFormat.FontName = "Corbel Light";

                    // Reset font size for it
                    textRange.CharacterFormat.FontSize = 11;

                    // Reset text color for it
                    textRange.CharacterFormat.TextColor = Color.Blue;

                    // Apply italic to the text range 
                    textRange.CharacterFormat.Italic = true;
                }
            }

            // Save the document to a different Word file
            document.SaveToFile("ChangeFont.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

C#: Edit Word Documents

Add New Elements to a Word Document in C#

In addition to modifying the existing content in a Word document, you can also insert various types of new elements, such as text, images, tables, lists, and charts. As most elements are paragraph-based, you have the flexibility to add a new paragraph at the end of the document or insert it mid-document. You can then populate this new paragraph with the desired content, whether that's plain text, images, or other elements.

Below are the steps to add new elements (text and images) to a Word document using C#:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Add a paragraph to the section using Section.AddParagraph() method.
  • Add text to the paragraph using Paragraph.AppendText() method.
  • Add an image to the paragraph using Paragraph.AppendPicture() method.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace AddNewElementsToWord
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new document object
            Document document = new Document();

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get the last section
            Section lastSection = document.LastSection;

            // Add a paragraph to the section
            Paragraph paragraph = lastSection.AddParagraph();

            // Add text to the paragraph
            paragraph.AppendText("This text and the image shown below are added programmatically using C# and Spire.Doc for .NET.");

            // Add an image to the paragraph
            paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\logo.png");

            // Create a paragraph style
            ParagraphStyle style = new ParagraphStyle(document);
            style.Name = "FontStyle";
            style.CharacterFormat.FontName = "Times New Roman";
            style.CharacterFormat.FontSize = 12;
            document.Styles.Add(style);

            // Apply the style to the paragraph
            paragraph.ApplyStyle(style.Name);

            // Save the document to a different Word file
            document.SaveToFile("AddNewElements.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

C#: Edit Word Documents

Remove Paragraphs from a Word Document in C#

With the Spire.Doc library, you can perform a variety of document operations, including updating existing content, adding new elements, as well as removing elements from a Word document. For example, to remove a paragraph from the document, you can use the Section.Paragraphs.RemoveAt() method.

The following are the steps to remove paragraphs from a Word document using C#:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Get a specific section through Document.Sections[index] property.
  • Remove a specific paragraph from the section using Section.Paragraphs.RemoveAt() method.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;

namespace RemoveParagraphs
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new document object
            Document document = new Document();

            // Load an existing Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get a specific section
            Section section = document.Sections[0];

            // Remove a specific paragraph
            section.Paragraphs.RemoveAt(0);

            // Save the document to a different Word file
            document.SaveToFile("RemoveParagraph.docx", FileFormat.Docx);

            // Dispose resource
            document.Dispose();
        }
    }
}

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Thursday, 08 August 2024 01:15