您的瀏覽器不支援JavaScript功能,若網頁功能無法正常使用時,請開啟瀏覽器JavaScript狀態
Antfire 的生活雜記
Skip
    banner

    使用 NPOI 在Word文件加入頁首小筆記

    使用 NPOI 在Word文件加入頁首小筆記

    程式碼

    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);
    
    	}

    重點回顧

    1. 宣告一個CT_Hdr 物件
    2. XWPFDocument 呼叫 CreateRelationship方法,接著設定Header
      var myHeader = doc.CreateRelationship(XWPFRelation.HEADER, XWPFFactory.GetInstance(), doc.HeaderList.Count + 1) as XWPFHeader; 
      myHeader.SetHeaderFooter(header);
    3. 在Section設定Header參考
      var section = body.sectPr;
      CT_HdrFtrRef myHeaderRef = section.AddNewHeaderReference();
      
      myHeaderRef.type = ST_HdrFtr.@default;
      
      myHeaderRef.id = myHeader.GetPackageRelationship().Id;

    結果截圖

    img-2023-04-25_09-17-14.jpg

     Comments