Apache POI设置Word文档首页禁用默认页脚问题咨询
解决方法
核心问题是你没有给文档第一节配置「首页页眉页脚不同」的属性,Word默认不会区分首页和其他页的页脚,即使你创建了FIRST类型的页脚也不会生效。
修改步骤
- 在创建完
XWPFHeaderFooterPolicy实例后,新增第一节的首页页脚不同配置 - 原有DEFAULT和FIRST类型页脚的创建逻辑可以保留,FIRST页脚留空即可实现首页无页脚
修改后完整代码
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr; import org.apache.poi.xwpf.usermodel.*; import org.apache.poi.ss.usermodel.ParagraphAlignment; private XWPFDocument initDocument(String FILE) throws Exception{ XWPFDocument document = new XWPFDocument(); XWPFHeaderFooterPolicy headerFooterPolicy = document.getHeaderFooterPolicy(); if (headerFooterPolicy == null) headerFooterPolicy = document.createHeaderFooterPolicy(); // 新增配置:开启第一节首页页眉页脚不同 CTSectPr sectPr = document.getDocument().getBody().isSetSectPr() ? document.getDocument().getBody().getSectPr() : document.getDocument().getBody().addNewSectPr(); if (!sectPr.isSetTitlePg()) { sectPr.addNewTitlePg(); } // 创建默认页脚(除首页外所有页面使用) XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT); XWPFParagraph paragraph = footer.getParagraphArray(0); if (paragraph == null) paragraph = footer.createParagraph(); paragraph.setAlignment(ParagraphAlignment.CENTER); XWPFRun run = paragraph.createRun(); run.setFontSize(11); run.setFontFamily("Times New Roman"); run.setText("Some company info in the footer"); // 创建首页页脚(留空即可不显示内容) XWPFFooter footerFirst = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.FIRST); paragraph = footerFirst.getParagraphArray(0); if (paragraph == null) paragraph = footerFirst.createParagraph(); // 不需要空行占高度可以设置段落边距为0 paragraph.setSpacingAfter(0); paragraph.setSpacingBefore(0); return document; }
额外说明
如果开启配置后首页还是有默认页脚的横线,将FIRST页脚的段落边框设置为无即可消除。
内容的提问来源于stack exchange,提问作者iteyran
相关产品推荐
相关产品推荐

