0
我試圖向.docx文件插入一個新區域。插入部分的功能應與通過文字處理器添加部分的方式相同。我正在使用Docx4j庫執行此任務。在Docx4J中爲.docx文件創建一個新區域
下面是代碼,我用它來創建新的.docx文件和:
- 添加段落包含運行和文字
- 添加「連續」部分的文件
- 添加另一段,包含運行和文本
將文檔保存到文件
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); // create new paragraph with a run containing text and add it to the document. P paragraph1 = objectFactory.createP(); // create new paragraph R run1 = objectFactory.createR(); // create new run Text text1 = objectFactory.createText(); // create text text1.setValue("This is text in paragraph 1 that should be located in section 1."); run1.getContent().add(text1); // add text ton the run paragraph1.getContent().add(run1); // add run to paragraph wordMLPackage.getMainDocumentPart().addObject(paragraph1); // add to main document part // create new section and add it to the document SectPr sectPr = objectFactory.createSectPr(); // create new section SectPr.Type sectPrType = objectFactory.createSectPrType(); sectPrType.setVal("continuous"); // "continuous" means no page break before section sectPr.setType(sectPrType); wordMLPackage.getMainDocumentPart().addObject(sectPr); // add section to document part // proceed to create another paragraph with a run containing text. P paragraph2= objectFactory.createP(); // create new paragraph R run2 = objectFactory.createR(); // create new run Text text2 = objectFactory.createText(); // create text text2.setValue("This is text in paragraph 2 that should be located in section 2."); run2.getContent().add(text2); // add text ton the run paragraph2.getContent().add(run2); // add run to paragraph wordMLPackage.getMainDocumentPart().addObject(paragraph2); // add to main document part wordMLPackage.save(new java.io.File("should contain_two_sections.docx")); // save
創建的文件包含代碼中定義的段落。該部分可能丟失或者僅僅因爲通過文字處理器(即LibreOffice Writer或Microsoft Word)「正常」插入部分而不起作用。
我已經閱讀了Docx4J文檔,SO問題如this和GitHub倉庫中的Docx4J examples,但是我還沒有找到任何工作示例來添加所描述的功能。