gpt4 book ai didi

java - 无效的 Apache POI HeaderFooterType.EVEN

转载 作者:行者123 更新时间:2023-12-02 11:10:50 26 4
gpt4 key购买 nike

Apache poi 3.17

XWPFDocument document = new XWPFDocument();
document
.createHeader(HeaderFooterType.EVEN)
.createParagraph()
.createRun()
.setText("even");

生成的Word文档中没有任何内容

enter image description here

HeaderFooterType.DEFAULT or HeaderFooterType.FIRST

这两个是有效的

document
.createHeader(HeaderFooterType.DEFAULT)
.createParagraph()
.createRun()
.setText("default");

enter image description here

最佳答案

到目前为止apache poi缺少设置 <w:evenAndOddHeaders/>/word/settings.xml 。但是,当 Word 中使用不同的奇数/偶数 header 时,这是必要的。 .

不幸的是,似乎没有一种方法可以获取 XWPFSettings和低水平org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSettings 。因此,我在示例中使用了 Reflection API。

import java.io.*;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;

import java.lang.reflect.Field;

public class CreateWordHeaderFooterType {

public static void main(String[] args) throws Exception {

XWPFDocument document= new XWPFDocument();

XWPFParagraph paragraph;
XWPFRun run;

// the body content
paragraph = document.createParagraph();
run=paragraph.createRun();
run.setText("Lorem ipsum.... page 1");

paragraph = document.createParagraph();
run=paragraph.createRun();
run.addBreak(BreakType.PAGE);
run.setText("Lorem ipsum.... page 2");

// create even header
document
.createHeader(HeaderFooterType.EVEN)
.createParagraph()
.createRun()
.setText("even");


// set evenAndOddHeaders in settings.xml
Field _settings = XWPFDocument.class.getDeclaredField("settings");
_settings.setAccessible(true);
XWPFSettings xwpfsettings = (XWPFSettings)_settings.get(document);
Field _ctSettings = XWPFSettings.class.getDeclaredField("ctSettings");
_ctSettings.setAccessible(true);
org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSettings ctsettings =
(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSettings)_ctSettings.get(xwpfsettings);

ctsettings.addNewEvenAndOddHeaders();


document.write(new FileOutputStream("CreateWordHeaderFooterType.docx"));
document.close();

}
}

关于java - 无效的 Apache POI HeaderFooterType.EVEN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50637707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com