Split a Word document into multiple documents by section break in C#

In Word, we can split a word document in an easiest way - open a copy of the original document, delete the sections that we don’t want and then save the remains to local drive. But doing this section by section is rather cumbersome and boring. This article will explain how we can use Spire.Doc for .NET to programmatically split a Word document into multiple documents by section break instead of copying and deleting manually.

Detail steps and code snippets:

Step 1: Initialize a new word document object and load the original word document which has two sections.

Document document = new Document();
document.LoadFromFile("Test.docx");

Step 2: Define another new word document object.

Document newWord;

Step 3: Traverse through all sections of the original word document, clone each section and add it to a new word document as new section, then save the document to specific path.

for (int i = 0; i < document.Sections.Count; i++)
{
    newWord = new Document();
    newWord.Sections.Add(document.Sections[i].Clone());
    newWord.SaveToFile(String.Format(@"test\out_{0}.docx", i));
}

Run the project and we'll get the following output:

How to split a Word document into multiple documents by section break in C#

Full codes:

using System;
using Spire.Doc;

namespace Split_Word_Document
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("Test.doc");
            Document newWord;
            for (int i = 0; i < document.Sections.Count; i++)
            {
                newWord = new Document();
                newWord.Sections.Add(document.Sections[i].Clone());
                newWord.SaveToFile(String.Format(@"test\out_{0}.docx", i));
            }
        }
    }
}