DocX

DocX – Add nested lists to Microsoft Word document programmatically

If you had one of those days looking for solution on how to easily add a nested list to Microsoft Word document by using C# search no more. Below you can find an example on how to do that using DocX package.

Prerequisites

Following prerequisites are required to create Microsoft Word document programmatically:

DocX package
Visual Studio 2013 / Visual Studio 2015 (Free Community Edition will do)
Basic understanding on how to code in C# (C Sharp)
Basic tutorial on how to start coding with DocX package can be found on our blog post DocX – A short tutorial for beginners HelloWorld()

Example code

Following code provides basic example on how to add Nested Lists to Microsoft Word programmatically.

private static void AddList()
{
    Console.WriteLine("\tAddList()");

    using (var document = DocX.Create(@"docs\Lists.docx"))
    {
        var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered);
                //Add a numbered list starting at 2
        document.AddListItem(numberedList, "Second List Item.");
        document.AddListItem(numberedList, "Third list item.");
        document.AddListItem(numberedList, "First sub list item", 1);

        document.AddListItem(numberedList, "Nested item.", 2);
        document.AddListItem(numberedList, "Fourth nested item.");

        var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
        document.AddListItem(bulletedList, "Second bullet item");
        document.AddListItem(bulletedList, "Sub bullet item", 1);
        document.AddListItem(bulletedList, "Second sub bullet item", 2);
        document.AddListItem(bulletedList, "Third bullet item");

        document.InsertList(numberedList);
        document.InsertList(bulletedList);
        document.Save();
        Console.WriteLine("\tCreated: docs\\Lists.docx");
    }
}

Example Output

Code above should create an output file called Lists.docx. If you start it up the view should be showing nice Nested Lists.

Example Notes

Above example is part of DocX Examples and can be found in DocX source package under Examples \ Program.cs. This example uses RelativeDirectory.cs class. It's required for the code sample to work and are included in the sources of DocX.

Keep that in mind when working with the code to either download the DocX package or change the code appropriately. Below you can find Relative Directory class just in case you have no access to sources.

using System;
using System.IO;

namespace Examples
{
    class RelativeDirectory
    {
        // Author D. Bolton see https://cplus.about.com (c) 2010
        private DirectoryInfo _dirInfo;

        public string Dir
        {
            get
            {
                return _dirInfo.Name;
            }
        }

        public string Path
        {
            get { return _dirInfo.FullName; }
            set
            {
                try
                {
                    DirectoryInfo newDir = new DirectoryInfo(value);
                    _dirInfo = newDir;
                }
                catch
                {
                    // silent
                }
            }
        }
        public RelativeDirectory()
        {
            _dirInfo = new DirectoryInfo(Environment.CurrentDirectory);
        }

        public RelativeDirectory(string absoluteDir)
        {
            _dirInfo = new DirectoryInfo(absoluteDir);
        }

        public Boolean Up(int numLevels)
        {
            for (int i = 0; i < numLevels; i++)
            {
                DirectoryInfo tempDir = _dirInfo.Parent;
                if (tempDir != null)
                    _dirInfo = tempDir;
                else
                    return false;
            }
            return true;
        }

        public Boolean Up()
        {
            return Up(1);
        }

        public Boolean Down(string match)
        {
            DirectoryInfo[] dirs = _dirInfo.GetDirectories(match + '*');
            _dirInfo = dirs[0];
            return true;
        }

    }

}

This post was last modified on %s = human-readable time difference 14:35

Przemyslaw Klys

System Architect with over 14 years of experience in the IT field. Skilled, among others, in Active Directory, Microsoft Exchange and Office 365. Profoundly interested in PowerShell. Software geek.

Share
Published by
Przemyslaw Klys

Recent Posts

Upgrade Azure Active Directory Connect fails with unexpected error

Today, I made the decision to upgrade my test environment and update the version of…

1 miesiąc ago

Mastering Active Directory Hygiene: Automating Stale Computer Cleanup with CleanupMonster

Have you ever looked at your Active Directory and wondered, "Why do I still have…

2 miesiące ago

Active Directory Replication Summary to your Email or Microsoft Teams

Active Directory replication is a critical process that ensures the consistent and up-to-date state of…

7 miesięcy ago

Syncing Global Address List (GAL) to personal contacts and between Office 365 tenants with PowerShell

Hey there! Today, I wanted to introduce you to one of the small but excellent…

11 miesięcy ago

Active Directory Health Check using Microsoft Entra Connect Health Service

Active Directory (AD) is crucial in managing identities and resources within an organization. Ensuring its…

1 rok ago

Seamless HTML Report Creation: Harness the Power of Markdown with PSWriteHTML PowerShell Module

In today's digital age, the ability to create compelling and informative HTML reports and documents…

1 rok ago