Skip to main content Skip to footer

How to Programmatically Create Word DOCX Files in C# .NET

Quick Start Guide
Tutorial Concept

Learn how to programmatically create Word .docx files from scratch using a .NET Word API. Using this API, developers can add data, customize the appearance, and save the DOCX file using C#.

What You Will Need

NuGet Packages: DS.Documents.Word

.NET 8+

Visual Studio (This example uses VS2022)

Controls Referenced

Document Solutions for Word - .NET Word API

Online Demo Explorer | Documentation | Other Word API Blogs

Enterprise-level software developers often face the challenge of managing Word documents programmatically in their applications. From automating document creation to generating data-driven reports and ensuring seamless workflows, a robust .NET Word API offers the tools to streamline these tasks. These APIs enable developers to create, edit, and export Word documents with precision, eliminating dependencies on external software like Microsoft Word while maintaining full control over the output.

In this guide, we’ll demonstrate how to leverage the .NET Word API, Document Solutions for Word, to programmatically create Word documents, showcasing its capabilities to simplify server-side document processing in enterprise applications.

Download the Latest Release of Document Solutions for Word Today!

Steps to Generate a Word DOCX File Using C# .NET

  1. Create a .NET Console Application – Includes installing a Word API
  2. Initialize the .NET Server-Side .DOCX File – Invoking the GcWordDocument Class
  3. Programmatically Set Word Document Properties
  4. Add Text to the Word Document Paragraphs using C#
    • Adding Text Using the GetRange Method
    • Adding Text Using the AddParagraph Method
  5. Read Data into a DOCX File using C#
  6. Programmatically Save a Word .DOCX File using C# – Invoking the Save Method

Download a finished C# .NET 8 Console Sample Application here.

Create a .NET Console Application

Open Visual Studio 2022 and create a new Console App; for this example, we created a C# app and named it DsWord_Create_DOCX.

Create a C# Console Application
Create a C# Console Application

For this example, we will be using .NET 8.

Create a .NET 8 Console App to Create a DOCX Files
Create a .NET 8 Console App to Create a DOCX Files

Right-click the project in the Solution Explorer and choose Manage NuGet Packages. In the Package source at the top right, select NuGet.org. Click the Browse tab on the top left and search for "DS.Documents." On the left panel, select DS.Documents.Word.

.NET Word API NuGet Package - Ds.Documents.Word
.NET Word API NuGet Package - Ds.Documents.Word

Add the needed namespace to the Program.cs file:

using GrapeCity.Documents.Word;

Initialize the .NET Server-Side .DOCX File

Initialize the server-side Word DOCX file instance by invoking the GcWordDocument class in the main function of Program.cs. This creates a new .NET Word document object.

// Create a new Word document:
GcWordDocument doc = new GcWordDocument();

Programmatically Set Word Document Properties

A .NET Word API allows developers to configure document-wide settings, such as compatibility and view options, to customize how a document behaves or appears. Our Settings class API enables access to properties like CompatibilityOptions and ViewOptions to fine-tune the MS Word document compatibility and layout.

// Set compatibility mode and print view
doc.Settings.CompatibilityOptions.CompatibiltyMode = WordVersion.Word2007;
doc.Settings.ViewOptions.ViewType = ViewType.Print;

Explore our Document Properties documentation to learn more about the additional MS Word document features supported by this .NET API.


Add Text to the Word Document Paragraphs using C#

The .NET Word API includes helper methods to simplify adding content, making code shorter, clearer, and more accessible. Below, we explore two ways to add text to a DOCX document. In this example, we will create and stylize titles. For more details, see the Helper Methods for Adding Content.

Adding Text Using the GetRange Method

To add text to a document, you can access the first section from the document’s body using the GetRange method. Once you have the range, you can add a paragraph to the paragraph collection by calling the Add method of the ParagraphCollection class. This approach provides flexibility when working directly with specific ranges within the document.

// Add and format the first title using GetRange
Paragraph p = doc.Body.Sections.First.GetRange().Paragraphs.Add("Introduction");
p.Format.Alignment = ParagraphAlignment.Center;
Run run = p.GetRange().Runs.First;
run.Font.Size = 20;
run.Font.Name = "Arial";

Adding Text Using the AddParagraph Method

Alternatively, you can add a paragraph directly to the paragraph collection by using the AddParagraph method of the Body class. This method simplifies the process by allowing you to append text directly to the document body without accessing a specific range.

// Add and format the second title using AddParagraph
p = doc.Body.AddParagraph("The Importance of Wetlands");
p.Format.Alignment = ParagraphAlignment.Center;
run = p.GetRange().Runs.First;
run.Font.Size = 16;
run.Font.Name = "Arial";

After applying the above code, the backend .NET Word document now contains the following:

Add titles to a MS Word DOCX File using C Sharp
Add titles to a MS Word DOCX File using C Sharp

Read Data into a DOCX File using C#

A .NET Word API allows developers to seamlessly import and structure text data within Word documents. By reading content from an external source, such as a text file, paragraphs can be dynamically created and styled to maintain consistent formatting. The .NET Word API provides flexibility to detect blank lines, apply predefined styles, and ensure text is properly structured. With efficient text processing capabilities, developers can automate document generation while maintaining readability and professional formatting.

First, let’s set the style for the paragraph and characters we plan to add to the DOCX file. This is accomplished using the Styles property of the GcWordDocument class.

// Set stles for paragraph
var pStyle = doc.Styles.Add("par style 1", StyleType.Paragraph);
pStyle.ParagraphFormat.Indentation.FirstLineIndent = 36;
pStyle.ParagraphFormat.Alignment = ParagraphAlignment.Left;
// Set styles for characters
var cStyle = doc.Styles.Add("char style 1", StyleType.Character);
cStyle.Font.Size = 9;

The text file is opened using a StreamReader, and each line is read one at a time for processing.

using (System.IO.StreamReader file = new System.IO.StreamReader(@"TheImportanceOfWetlands.txt"))
{
    string line;
    Paragraph currentParagraph = null;
}

Each line is trimmed to remove unnecessary spaces. If the line is not blank, a new paragraph is created using the Add method of the RangeBase’s Paragraphs property or appended to the current paragraph.

    while ((line = file.ReadLine()) != null)
    {
        // Trim the line to remove any leading/trailing spaces
        line = line.Trim();

        // Create a new paragraph for non-blank lines
        if (!string.IsNullOrWhiteSpace(line))
        {
            if (currentParagraph == null)
            {
                currentParagraph = doc.Body.Sections.First.GetRange().Paragraphs.Add();
                currentParagraph.Style = pStyle;
            }

Each trimmed line is added to the current paragraph as a run using the Runs property of the RangeBase class with a space appended to prevent words from merging.

            // Add the line to the current paragraph
            run = currentParagraph.GetRange().Runs.Add(line + " ");
            // Add a space at the end of each line
            run.Style = cStyle;
        }

Blank lines reset the currentParagraph to ensure that subsequent text creates a new paragraph.

        else
        {
            // Reset the paragraph for the next block of text
            currentParagraph = null;
        }
    }
}

With this code logic, the content from the TXT file is added to the server-side DOCX file and now appears like so:

Read External Content into Server-Side DOCX File using C#

This programmatic approach ensures structured formatting while dynamically inserting text from an external file into a Word document.


Programmatically Save a Word .DOCX File in C#

Save the server-side MS Word document using the API’s Save method of the DsWordDocument class.

//Save the created Word file
doc.Save("CreateDoc.docx");

Ready to try it out? Download Document Solutions for Word Today!


Learn More About this C# .NET Word API

This article only scratches the surface of the full capabilities of Document Solutions for Word, our .NET Word API library. We recommend checking out the next blog in this series, Load, Modify, and Save Word Documents in .NET Applications, or visit our online demo explorer and documentation to learn more.

Tags:

comments powered by Disqus