Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Fri Jun 07, 2024 8:42 am

您好,我在参考文档进行文档合并时使用了如下代码,两个文档中均有相同样式(标题一)的编号(2.docx由1.docx复制得到);此时合并的文档中的编号并没有继续编号而是重新开始。类似于如下格式,请问如何操作能够使得拼接上去的内容能够从4继续编号呢
1. 二
2. 三
3. 四
1. 二………………

public static void main(String[] args) throws Exception{
//创建两个Document对象并加载两个示例文档
Document document1 = new Document("D:\\1.docx");
Document document2 = new Document("D:\\2.docx");

//遍历第二个文档,获取所有节
for (Object sectionObj : document2.getSections()) {
Section sec=(Section)sectionObj;
//遍历第二个文档的所有节,获取其子对象
for (Object docObj : sec.getBody().getChildObjects()) {
DocumentObject obj=(DocumentObject)docObj;

//获取第一个文档的最后一节
Section lastSection = document1.getLastSection();
//lastSection = document1.getSections().get(1);
//将子对象添加到第一个文档的最后一节中
Body body = lastSection.getBody();
body.getChildObjects().add(obj.deepClone());
}
}
//String listText = paragraph.getListText();
//保存结果文档
document1.saveToFile("result2.docx", FileFormat.Docx);
}

18810336217
 
Posts: 1
Joined: Fri Jun 07, 2024 8:30 am

Fri Jun 07, 2024 10:13 am

您好,

感谢您的咨询。
我们产品不会将两个文档的编号进行合并,因为它们对应的编号样式实际上是不一样的。您可以先获取到第一个文档段落对应的编号样式,在文档合并之后对应的段落应用这个样式,就能是现实继续编号的效果。请参考下面的代码片段进行测试,如果您还有任何疑问,请随时来信。
Code: Select all
// 文档合并代码
...
// 获取第一个文档的第一个段落应用的ListStyle
ListStyle currentListStyle = document1.getSections().get(0).getParagraphs().get(0).getListFormat().getCurrentListStyle();
// 将合并后的文档段落都应用为这个ListStyle
for (Object sectionObj : document1.getSections()) {
    Section sec=(Section)sectionObj;
    for (Object docObj : sec.getBody().getChildObjects()) {
        DocumentObject obj=(DocumentObject)docObj;
        if(obj instanceof Paragraph){
            Paragraph paragraph = (Paragraph) obj;
            paragraph.getListFormat().applyStyle(currentListStyle.getName());
        }
    }
}
document1.saveToFile("res.docx", FileFormat.Docx);

Sincerely
William
E-iceblue support team
User avatar

William.Zhang
 
Posts: 451
Joined: Mon Dec 27, 2021 2:23 am

Return to Spire.Doc