spire.doc支持复制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)
复制结果: