How C # Merges and splits Word documents

Source: Internet
Author: User

Overview

For easy document management, storage, and transport, we often want to split some documents into multiple subdocuments, or merge multiple documents into one document. In this article, you'll describe the methods for splitting and merging Word documents. The following example will contain these points:

    1. Merging Word documents
      1.1 Create a new page to merge into a document
      1.2 Merge to document immediately above
    2. Splitting a Word document
      2.1 Splitting by section break
      2.2 Split by Page break
The tools used
    • Free Spire.doc for. NET 6.3
    • Visual Studio
Example operations

First, Merge Word documents
(i) Merging new pages into documents
"C #"

using Spire.Doc;namespace MergeWord_Doc{    class Program    {        static void Main(string[] args)        {            //创建两个文档,加载需要合并的文件            Document doc1 = new Document(@"C:\Users\Administrator\Desktop\TradeNegotiation.docx");            Document doc2 = new Document(@"C:\Users\Administrator\Desktop\DisputeSettlement.docx");            //调用InsertTextFromFile()方法,将文档2合并到文档1            string fileName = @"C:\Users\Administrator\Desktop\DisputeSettlement.docx";            doc1.InsertTextFromFile(fileName, FileFormat.Docx2013);            //保存文件            doc1.SaveToFile("MergedDocument.docx", FileFormat.Docx2013);        }    }}

Debug run the project, generate the file as shown in:

(ii) Immediately following the merger into the document
"C #"

using Spire.Doc;using Spire.Doc.Documents;namespace MergeWord2_Doc{    class Program    {        static void Main(string[] args)        {            //创建两个文档,并加载需要合并的两个文件            Document doc1 = new Document(@"C:\Users\Administrator\Desktop\TradeNegotiation.docx");            Document doc2 = new Document(@"C:\Users\Administrator\Desktop\DisputeSettlement.docx");            //获取文档1的最后一个Section            Section lastSection = doc1.LastSection;            //遍历文档2中的所有section,复制所有section到文档1            foreach (Section section in doc2.Sections)            {                foreach (Paragraph paragraph in section.Paragraphs)                {                    lastSection.Paragraphs.Add(paragraph.Clone() as Paragraph);                }            }            //将合并的文档另存为一个新文档            doc1.SaveToFile("Merged.docx", FileFormat.Docx2013);        }    }}

Merge effect:

Second, split Word document
(i) Split by section break
"C #"

using Spire.Doc;using System;namespace SplitWord_Doc{    class Program    {        static void Main(string[] args)        {            //创建一个Document类对象,并加载需要拆分的文档            Document document = new Document();            document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");            //实例化Document对象             Document newWord;            //遍历文档所有section,复制文档每个section并分别保存到新建的文档,同时将拆分的文档保存到指定路径            for (int i = 0; i < document.Sections.Count; i++)            {                newWord = new Document();                newWord.Sections.Add(document.Sections[i].Clone());                newWord.SaveToFile(String.Format(@"results\out_{0}.docx", i));            }        }    }}

Split effect:

(ii) Split by page break
"C #"

Using system;using spire.doc;using Spire.doc.documents;namespace split_word_document_by_page_break{class Program { static void Main (string[] args) {//instantiating a document class, loading document document original = new Docume            NT (); Original.            LoadFromFile (@ "C:\Users\Administrator\Desktop\test.docx");            Instantiate the document class object and add section Document Newword = new Document ();            Section section = Newword.addsection ();            Splits a document according to pagination int index = 0; Traverse the document all sections of foreach (section sec in original. Sections) {//Traverse document all child objects foreach (DocumentObject obj in sec. Body.childobjects) {if (obj is Paragraph) {P                        Aragraph para = obj as Paragraph; Copy and add the original paragraph object to the new document section. BODY.CHILDOBJECTS.ADD (para.                        Clone ());                Traverse all paragraph sub-objects        foreach (DocumentObject parobj in para. Childobjects) {if (Parobj is break && (parobj as Break).                                Breaktype = = Breaktype.pagebreak) {//Get paragraph pagination and remove, save new document to Folder int i = para.                                Childobjects.indexof (Parobj); Section.                                Body.LastParagraph.ChildObjects.RemoveAt (i);                                Newword.savetofile (String.Format ("Results/out-{0}.docx", Index), fileformat.docx);                                index++;                                Instantiate the document class object, add a section, copy the child objects of the original document paragraph to the new document Newword                                Section = Newword.addsection (); Section. BODY.CHILDOBJECTS.ADD (para.                                Clone ()); if (section. Paragraphs[0].                         Childobjects.count = = 0) {           Remove the first blank paragraph section.                                Body.ChildObjects.RemoveAt (0);                                    } else {//delete sub-objects before page break                                                                                while (I >= 0) { Section. Paragraphs[0].                                        Childobjects.removeat (i);                                    i--;                    }                                }                            }                        }                    } If the object is a table, add the Table object to the new document if (obj is table) {section. BODY.CHILDOBJECTS.ADD (obj.                    Clone ()); }}}//The new document after splitting is saved to the specified document Newword.savetofile (String.Format ("Results/out-{0}.d        OCX ", index), fileformat.docx); }   }} 

Split effect:

Read the end.
If you want to reprint, please specify the source!

How C # Merges and splits Word documents

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.