在使用MS Word时,用户可以点击“插入”-“对象”-“文件中的文字”快速将选定文件中的文本插入当前文档。
Spire.Doc提供了类似的方法InsertTextFromFile来将不同的文档合并到同一个文档,但与Word的差别在于,目前InsertTextFromFile方法不支持选定插入位置。使用该方法合并文档时,新加入的文档默认从新的一页开始显示。如果需要新添加的文档承接前一个文档的段尾,则需要使用不同的合并方法。本文将分别介绍如何使用Spire.Doc实现两种不同的合并效果。
添加新页合并
//获取文档路径
string filePath_1 = @"C:\Users\Administrator\Desktop\Word_1.docx";
string filePath_2 = @"C:\Users\Administrator\Desktop\Word_2.docx";
//加载文档1到Document对象
Document doc= new Document(filePath_1);
//使用InsertTextFromFile方法将文档2合并到新文档
doc.InsertTextFromFile(filePath_2, FileFormat.Docx2013);
//保存文档
doc.SaveToFile("合并文档.docx", FileFormat.Docx2013);
承接前一个文档的段尾合并
这种合并方法的思想是获取第一个文档的最后一个section,然后将其余被合并文档的段落作为新的段落添加到section。
//初始化两个Document实例并加载两个测试文档
Document doc1 = new Document(@"C:\Users\Administrator\Desktop\测试文档_1.docx");
Document doc2 = new Document(@"C:\Users\Administrator\Desktop\测试文档_2.docx");
//获取doc1的最后一个section
Section lastSection = doc1.LastSection;
//遍历doc2的section及其子对象,将每一个子对象添加doc1的最后一个section
foreach (Section section in doc2.Sections)
{
foreach(DocumentObject obj in section.Body.ChildObjects)
{
lastSection.Body.ChildObjects.Add(obj.Clone());
}
}
//保存为新的文档
doc1.SaveToFile("合并文档_2.docx", FileFormat.Docx2013);