使用OpenXml SDK向Word文档中添加页、段落、页眉和页脚

1. 创建word文档作为模版

2. 以下代码实现需求

[csharp]  view plain copy
  1. using DocumentFormat.OpenXml.Packaging;  
  2. using System.IO;  
  3. using DocumentFormat.OpenXml.Wordprocessing;  
  4.   
  5. namespace OpenXmlAddParagraphsToNewPage  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             if (File.Exists("copy.docx"))  
  12.             {  
  13.                 File.Delete("copy.docx");  
  14.             }  
  15.   
  16.             File.Copy("InsertNewPageAndParagraphs.docx""copy.docx");  
  17.             using (WordprocessingDocument doc = WordprocessingDocument.Open("copy.docx"true))  
  18.             {  
  19.                 var body = doc.MainDocumentPart.Document.Body;  
  20.   
  21.                 Paragraph newPara = new Paragraph(new Run  
  22.                      (new Break() { Type = BreakValues.Page },  
  23.                      new Text("text on the new page")));  
  24.   
  25.                 body.Append(newPara);  
  26.   
  27.                 AddHeader(doc);  
  28.                 AddFooter(doc);  
  29.                 doc.MainDocumentPart.Document.Save();  
  30.             }  
  31.         }  
  32.   
  33.         private static void AddFooter(WordprocessingDocument doc)  
  34.         {  
  35.             // Declare a string for the header text.  
  36.             string newFooterText =  
  37.               "New footer via Open XML Format SDK 2.0 classes";  
  38.   
  39.             // Get the main document part.  
  40.             MainDocumentPart mainDocPart = doc.MainDocumentPart;  
  41.   
  42.             // Delete the existing footer parts.  
  43.             mainDocPart.DeleteParts(mainDocPart.FooterParts);  
  44.   
  45.             // Create a new footer part and get its relationship id.  
  46.             FooterPart newFooterPart = mainDocPart.AddNewPart<FooterPart>();  
  47.             string rId = mainDocPart.GetIdOfPart(newFooterPart);  
  48.   
  49.             // Call the GeneratePageFooterPart helper method, passing in  
  50.             // the footer text, to create the footer markup and then save  
  51.             // that markup to the footer part.  
  52.             GeneratePageFooterPart(newFooterText).Save(newFooterPart);  
  53.   
  54.             // Loop through all section properties in the document  
  55.             // which is where footer references are defined.  
  56.             foreach (SectionProperties sectProperties in  
  57.               mainDocPart.Document.Descendants<SectionProperties>())  
  58.             {  
  59.                 //  Delete any existing references to footers.  
  60.                 foreach (FooterReference footerReference in  
  61.                   sectProperties.Descendants<FooterReference>())  
  62.                     sectProperties.RemoveChild(footerReference);  
  63.   
  64.                 //  Create a new footer reference that points to the new  
  65.                 // footer part and add it to the section properties.  
  66.                 FooterReference newFooterReference =  
  67.                   new FooterReference() { Id = rId, Type = HeaderFooterValues.Default };  
  68.                 sectProperties.Append(newFooterReference);  
  69.             }  
  70.               
  71.             //  Save the changes to the main document part.  
  72.             mainDocPart.Document.Save();  
  73.         }  
  74.   
  75.         private static void AddHeader(WordprocessingDocument doc)  
  76.         {  
  77.             // Declare a string for the header text.  
  78.             string newHeaderText =  
  79.               "New header via Open XML Format SDK 2.0 classes";  
  80.   
  81.   
  82.             // Get the main document part.  
  83.             MainDocumentPart mainDocPart = doc.MainDocumentPart;  
  84.   
  85.             // Delete the existing header parts.  
  86.             mainDocPart.DeleteParts(mainDocPart.HeaderParts);  
  87.   
  88.             // Create a new header part and get its relationship id.  
  89.             HeaderPart newHeaderPart = mainDocPart.AddNewPart<HeaderPart>();  
  90.             string rId = mainDocPart.GetIdOfPart(newHeaderPart);  
  91.   
  92.             // Call the GeneratePageHeaderPart helper method, passing in  
  93.             // the header text, to create the header markup and then save  
  94.             // that markup to the header part.  
  95.             GeneratePageHeaderPart(newHeaderText).Save(newHeaderPart);  
  96.   
  97.             // Loop through all section properties in the document  
  98.             // which is where header references are defined.  
  99.             foreach (SectionProperties sectProperties in  
  100.               mainDocPart.Document.Descendants<SectionProperties>())  
  101.             {  
  102.                 //  Delete any existing references to headers.  
  103.                 foreach (HeaderReference headerReference in  
  104.                   sectProperties.Descendants<HeaderReference>())  
  105.                     sectProperties.RemoveChild(headerReference);  
  106.   
  107.                 //  Create a new header reference that points to the new  
  108.                 // header part and add it to the section properties.  
  109.                 HeaderReference newHeaderReference =  
  110.                   new HeaderReference() { Id = rId, Type = HeaderFooterValues.Default };  
  111.                 sectProperties.Append(newHeaderReference);  
  112.             }  
  113.   
  114.             //  Save the changes to the main document part.  
  115.             //mainDocPart.Document.Save();  
  116.   
  117.         }  
  118.   
  119.         // Creates an header instance and adds its children.  
  120.         private static Header GeneratePageHeaderPart(string HeaderText)  
  121.         {  
  122.             // set the position to be the center  
  123.             PositionalTab pTab = new PositionalTab()  
  124.             {  
  125.                 Alignment = AbsolutePositionTabAlignmentValues.Center,  
  126.                 RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,  
  127.                 Leader = AbsolutePositionTabLeaderCharValues.None  
  128.             };  
  129.   
  130.             var element =  
  131.               new Header(  
  132.                 new Paragraph(  
  133.                   new ParagraphProperties(  
  134.                     new ParagraphStyleId() { Val = "Header" }),  
  135.                   new Run(pTab,  
  136.                     new Text(HeaderText))  
  137.                 )  
  138.               );  
  139.   
  140.             return element;  
  141.         }  
  142.   
  143.         // Creates an Footer instance and adds its children.  
  144.         private static Footer GeneratePageFooterPart(string FooterText)  
  145.         {  
  146.             PositionalTab pTab = new PositionalTab()  
  147.             {  
  148.                 Alignment = AbsolutePositionTabAlignmentValues.Center,  
  149.                 RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,  
  150.                 Leader = AbsolutePositionTabLeaderCharValues.None  
  151.             };  
  152.   
  153.             var elment =  
  154.                 new Footer(  
  155.                     new Paragraph(  
  156.                         new ParagraphProperties(  
  157.                             new ParagraphStyleId() { Val = "Footer" }),  
  158.                         new Run(pTab,  
  159.                             new Text(FooterText))  
  160.                                 )  
  161.                             );  
  162.             return elment;  
  163.         }  
  164.     }  
  165. }  

3. 运行效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值