Spire.Doc支持复制Word文档,包括复制文本及文本格式、图片、表格、页眉、页脚等。在 C# 复制Word页眉页脚一文中介绍了复制页眉页脚的方法,本文将介绍如何使用Spire.Doc 复制Word文档。复制文档分为了以下两种情况:
- 复制整篇Word文档
- 复制Word文档中的指定段落
源文档:
复制整篇Word文档
目标文档:
C#
//新建Word文档1,用于加载待复制内容的源文档
Document sourceDoc = new Document("test.docx");
//新建Word文档2,用于加载复制内容的目标文档
Document destinationDoc = new Document("target.docx");
//遍历源word文档中的所有section,并把内容复制到目标word文档
foreach (Section sec in sourceDoc.Sections)
{
foreach (DocumentObject obj in sec.Body.ChildObjects)
{
destinationDoc.Sections[0].Body.ChildObjects.Add(obj.Clone());
}
}
//保存文档
destinationDoc.SaveToFile("result.docx", FileFormat.Docx2010);
VB.NET
Dim sourceDoc As Document = New Document("test.docx")
Dim destinationDoc As Document = New Document("target.docx")
For Each sec As Section In sourceDoc.Sections
For Each obj As DocumentObject In sec.Body.ChildObjects
destinationDoc.Sections(0).Body.ChildObjects.Add(obj.Clone)
Next
Next
destinationDoc.SaveToFile("result.docx", FileFormat.Docx2010)
复制结果:
复制指定段落内容
C#
//创建Word文档1,加载源文档
Document doc1 = new Document();
doc1.LoadFromFile("test.docx");
//创建一个空白文档,作为复制内容的目标文档
Document doc2 = new Document();
//获取Word文档1第一节的第2段和第3段
Section s = doc1.Sections[0];
Paragraph p1 = s.Paragraphs[1];
Paragraph p2 = s.Paragraphs[2];
//在Word文档2中添加Section,并将文档1中的第2、3段的内容复制到文档2中
Section s1 = doc2.AddSection();
Paragraph NewPara1 = (Paragraph)p1.Clone();
s1.Paragraphs.Add(NewPara1);
Paragraph NewPara2 = (Paragraph)p2.Clone();
s1.Paragraphs.Add(NewPara2);
//保存文档
doc2.SaveToFile("output.docx", FileFormat.Docx2010);
VB.NET
Dim doc1 As Document = New Document
doc1.LoadFromFile("test.docx")
Dim doc2 As Document = New Document
Dim s As Section = doc1.Sections(0)
Dim p1 As Paragraph = s.Paragraphs(1)
Dim p2 As Paragraph = s.Paragraphs(2)
Dim s1 As Section = doc2.AddSection
Dim NewPara1 As Paragraph = CType(p1.Clone,Paragraph)
s1.Paragraphs.Add(NewPara1)
Dim NewPara2 As Paragraph = CType(p2.Clone,Paragraph)
s1.Paragraphs.Add(NewPara2)
doc2.SaveToFile("output.docx", FileFormat.Docx2010)
复制结果: