java

您所在的位置:网站首页 目录的更新域的作用 java

java

2024-07-10 06:01| 来源: 网络整理| 查看: 265

我正在使用 Apache POI XWPF 组件和 java 将 .xml 文件中的数据提取到 Word 文档中。到目前为止一切顺利,但我正在努力创建目录。

我必须在方法开始时创建一个目录,然后在最后更新它以获取所有新 header 。目前,我使用 doc.createTOC()(其中 doc 是从 XWPFDocument 创建的变量)在开头创建表,然后使用 doc.enforceUpdateFields() 更新文档末尾的所有内容。但是,当我运行程序后打开文档时,目录是空的,但导航面板确实包含我指定的一些标题。

评论建议我添加一些代码。所以我首先从模板创建文档:

XWPFDocument doc = new XWPFDocument(new FileInputStream("D://Template.docx"));

然后我创建一个目录:

doc.createTOC();

然后在整个方法中我向文档添加标题:

XWPFParagraph documentControlHeading = doc.createParagraph(); documentControlHeading.setPageBreak(true); documentControlHeading.setAlignment(ParagraphAlignment.LEFT); documentControlHeading.setStyle("Tier1Header");

添加所有标题后,我想更新文档,以便所有新标题都出现在目录中。我使用以下命令进行购买:

doc.enforceUpdateFields();

最佳答案

//您的 docx 模板应包含以下或类似的文本//将搜索该文本并将其替换为 WORD 目录。

//${TOC}

public static void main(String[] args) throws IOException, OpenXML4JException { XWPFDocument docTemplate = null; try { File file = new File(PATH_TO_FILE); //"C:\\Reports\\Template.docx"; FileInputStream fis = new FileInputStream(file); docTemplate = new XWPFDocument(fis); generateTOC(docTemplate); saveDocument(docTemplate); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (docTemplate != null) { docTemplate.close(); } } } private static void saveDocument(XWPFDocument docTemplate) throws FileNotFoundException, IOException { FileOutputStream outputFile = null; try { outputFile = new FileOutputStream(OUTFILENAME); docTemplate.write(outputFile); } finally { if (outputFile != null) { outputFile.close(); } } } public static void generateTOC(XWPFDocument document) throws InvalidFormatException, FileNotFoundException, IOException { String findText = "${TOC}"; String replaceText = ""; for (XWPFParagraph p : document.getParagraphs()) { for (XWPFRun r : p.getRuns()) { int pos = r.getTextPosition(); String text = r.getText(pos); if (text != null && text.contains(findText)) { text = text.replace(findText, replaceText); r.setText(text, 0); addField(p, "TOC \\o \"1-3\" \\h \\z \\u"); break; } } } } private static void addField(XWPFParagraph paragraph, String fieldName) { CTSimpleField ctSimpleField = paragraph.getCTP().addNewFldSimple(); // ctSimpleField.setInstr(fieldName + " \\* MERGEFORMAT "); ctSimpleField.setInstr(fieldName); ctSimpleField.addNewR().addNewT().setStringValue(""); }

关于java - Apache POI 目录未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37454260/



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3