NPOI word 页眉 页脚

using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NPOI
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create document
            XWPFDocument doc = new XWPFDocument();
            XWPFParagraph para = doc.CreateParagraph();
            XWPFRun run = para.CreateRun();
            run.SetText("Spire.Doc for .NET");
            doc.Document.body.sectPr = new CT_SectPr();
            CT_SectPr secPr = doc.Document.body.sectPr;
            //Create header and set its text
            CT_Hdr header = new CT_Hdr();
            header.AddNewP().AddNewR().AddNewT().Value = "This is Header";
            //Create footer and set its text
            CT_Ftr footer = new CT_Ftr();
            footer.AddNewP().AddNewR().AddNewT().Value = "This is Footer";
            //Create the relation of header
            XWPFRelation relation1 = XWPFRelation.HEADER;
            XWPFHeader myHeader = (XWPFHeader)doc.CreateRelationship(relation1, XWPFFactory.GetInstance(), doc.HeaderList.Count + 1);
            //Create the relation of footer
            XWPFRelation relation2 = XWPFRelation.FOOTER;
            XWPFFooter myFooter = (XWPFFooter)doc.CreateRelationship(relation2, XWPFFactory.GetInstance(), doc.FooterList.Count + 1);
            //Set the header
            myHeader.SetHeaderFooter(header);
            CT_HdrFtrRef myHeaderRef = secPr.AddNewHeaderReference();
            myHeaderRef.type = ST_HdrFtr.@default;
            myHeaderRef.id = myHeader.GetPackageRelationship().Id;
            //Set the footer
            myFooter.SetHeaderFooter(footer);
            CT_HdrFtrRef myFooterRef = secPr.AddNewFooterReference();
            myFooterRef.type = ST_HdrFtr.@default;
            myFooterRef.id = myFooter.GetPackageRelationship().Id;
            //Save the file
            using (FileStream stream = File.Create("HeaderAndFooter.docx"))
            {
                doc.Write(stream);
            }
            //Launch
            System.Diagnostics.Process.Start("HeaderAndFooter.docx");
        }
    }
}

你可能感兴趣的:(NPOI word 页眉 页脚)