C# NPOI 导出word文档的页眉与页码

页眉可编辑颜色与字体选择

页脚显示当前页码与页码的总数


页眉插入的方法:

    XWPFDocument document = new XWPFDocument();
    CT_Ftr footer = new CT_Ftr();
    XWPFParagraph paragraph = new XWPFParagraph(footer.AddNewP(), document);
    paragraph.Alignment = ParagraphAlignment.CENTER;
    //paragraph.SetFontFamily(fontFamily, FontCharRange.None);
    // 添加字段表示当前页数
    XWPFRun runCurrentPage = paragraph.CreateRun();
    runCurrentPage.SetFontFamily("宋体", FontCharRange.None);
    runCurrentPage.SetColor("000000");
    runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.begin;
    runCurrentPage.GetCTR().AddNewInstrText().Value = "PAGE";
    runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.separate;
    runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.end;

页码的插入方法:
 

XWPFDocument document = new XWPFDocument();
CT_Ftr footer = new CT_Ftr();
XWPFParagraph paragraph = new XWPFParagraph(footer.AddNewP(), document);
paragraph.Alignment = ParagraphAlignment.CENTER;
//paragraph.SetFontFamily(fontFamily, FontCharRange.None);
// 添加字段表示当前页数
XWPFRun runCurrentPage = paragraph.CreateRun();
runCurrentPage.SetFontFamily("宋体", FontCharRange.None);
runCurrentPage.SetColor("000000");
runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.begin;
runCurrentPage.GetCTR().AddNewInstrText().Value = "PAGE";
runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.separate;
runCurrentPage.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.end;

// 添加分隔符 "/"
XWPFRun runSeparator = paragraph.CreateRun();
runSeparator.SetText(" / ");

// 添加字段表示总页数
XWPFRun runTotalPages = paragraph.CreateRun();
runTotalPages.SetFontFamily("宋体", FontCharRange.None);
runTotalPages.SetColor("000000");
runTotalPages.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.begin;
runTotalPages.GetCTR().AddNewInstrText().Value = "NUMPAGES";
runTotalPages.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.separate;
runTotalPages.GetCTR().AddNewFldChar().fldCharType = ST_FldCharType.end;

// 创建页脚关系
XWPFRelation relation = XWPFRelation.FOOTER;
XWPFFooter myFooter = (XWPFFooter)document.CreateRelationship(relation, XWPFFactory.GetInstance(), document.FooterList.Count + 1);
myFooter.SetHeaderFooter(footer);

 在节属性中添加页脚引用
CT_SectPr sectPr = document.Document.body.sectPr;
CT_HdrFtrRef footerRef = sectPr.AddNewFooterReference();
footerRef.type = ST_HdrFtr.@default;
footerRef.id = myFooter.GetPackageRelationship().Id;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值