程式碼
CT_Hdr header = new CT_Hdr();
var hP = header.AddNewP();
hP.pPr = new CT_PPr {
spacing = new CT_Spacing { after = 20, line = "360", lineRule = ST_LineSpacingRule.auto },
jc = new CT_Jc { val = ST_Jc.center },
rPr = new CT_ParaRPr {
b = new CT_OnOff { val = true },
rFonts = new CT_Fonts { eastAsia = "標楷體"},
sz = new CT_HpsMeasure { val = 34 } ,
szCs = new CT_HpsMeasure { val = 34 }
}
};
var hpr = hP.AddNewR();
hpr.rPr = new CT_RPr {
b = new CT_OnOff { val = true },
rFonts = new CT_Fonts { eastAsia = "標楷體" },
sz = new CT_HpsMeasure { val = 34 },
szCs = new CT_HpsMeasure { val = 34}
};
hpr.AddNewT().Value = "This is header";
XWPFDocument doc = new XWPFDocument();
var document = doc.Document;
var body = document.body;
if (!body.IsSetSectPr())
{
body.sectPr = new NPOI.OpenXmlFormats.Wordprocessing.CT_SectPr();
}
var section = body.sectPr;
var myHeader = doc.CreateRelationship(XWPFRelation.HEADER, XWPFFactory.GetInstance(), doc.HeaderList.Count + 1) as XWPFHeader;
myHeader.SetHeaderFooter(header);
CT_HdrFtrRef myHeaderRef = section.AddNewHeaderReference();
myHeaderRef.type = ST_HdrFtr.@default;
myHeaderRef.id = myHeader.GetPackageRelationship().Id;
using (var fileStream = new FileStream(@"{PATH}", FileMode.Create))
{
doc.Write(fileStream);
}
重點回顧
- 宣告一個
CT_Hdr
物件 - XWPFDocument 呼叫
CreateRelationship
方法,接著設定Headervar myHeader = doc.CreateRelationship(XWPFRelation.HEADER, XWPFFactory.GetInstance(), doc.HeaderList.Count + 1) as XWPFHeader;
myHeader.SetHeaderFooter(header);
- 在Section設定Header參考
var section = body.sectPr;
CT_HdrFtrRef myHeaderRef = section.AddNewHeaderReference();
myHeaderRef.type = ST_HdrFtr.@default;
myHeaderRef.id = myHeader.GetPackageRelationship().Id;
結果截圖