Divide Word document into sections using C#. Get the details to set the development environment, a list of steps to write the application, and a sample code to split Word document into sections using C#. You may filter the sections while converting them into a separate Word file.
Steps to Break Word Document into Sections using C#
- Set the environment to use Aspose.Words for .NET for dividing Word documents into sections
- Load the Word file into the Document class object for splitting the sections
- Iterate through all the sections in the loaded Word file
- Create a Section object by cloning the current section in the iteration
- Create a new empty Word file and Clear its default collection of sections
- Import the new section into the empty Word file and save it with the new name
- Iterate the process for all the remaining sections
These steps describe how to divide a Word document into sections using C#. Load the Word file, clone each section one by one, and add it to the sections collection of a new Word file. Save the newly created Word file with the selected section using the unique file name.
Code to Separate Word Document into Sections using C#
using Aspose.Words; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
License lic = new License(); | |
lic.SetLicense("license.lic"); | |
// Load the source Word document | |
Document doc = new Document("Sections.docx"); | |
// Iterate through all the sections | |
for (int iSectionCounter = 0; iSectionCounter < doc.Sections.Count; iSectionCounter++) | |
{ | |
// Clone the current section | |
Section section = doc.Sections[iSectionCounter].Clone(); | |
// Create a new empty Word document | |
Document newDoc = new Document(); | |
// Remove the default sections in the Word file | |
newDoc.Sections.Clear(); | |
// Import the section to the new document | |
Section newSection = (Section)newDoc.ImportNode(section, true); | |
newDoc.Sections.Add(newSection); | |
// Save the section as a separate Word file | |
newDoc.Save($"Word_Section_{iSectionCounter}.docx"); | |
} | |
} | |
} |
This code has demonstrated how to divide Word document into sections using C#. You can filter the sections by parsing the body contents of the cloned section and checking the NodeType property. You can save the output Word file in various other formats if required.
This article has taught us to divide a Word file into sections and save it as a separate Word file. If you want to remove all page beaks in a Word file, refer to the article on How to remove all page breaks in Word using C#.