继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

C# 操作Word页眉页脚(8种情况)——添加图/文页眉页脚、设置奇偶页/首页页眉页脚、不连续设置页码、复制/锁定/删除页眉页脚

Eiceblue
关注TA
已关注
手记 107
粉丝 9
获赞 48

在Word文档中,我们可以通过添加页眉、页脚的方式来丰富文档内容。添加页眉、页脚时,可以添加时间、日期、文档标题,文档引用信息、页码、内容解释、图片/LOGO等多种图文信息。同时也可根据需要调整文字或图片在页眉页脚的位置。而在比较复杂一点的文档中,对页眉页脚的添加要求比较严格的,如需要设置奇、偶页的页眉页脚不同、首页页眉页脚不同、设置页码时需要对不同章节的内容设置不同页码、对包含重要信息的页眉页脚需要设置编辑权限、相同性质的文档需要复制指定页眉页脚等等操作时,都可以参考本篇文章将要介绍的关于如何操作Word中的页眉页脚的方法。文章将从以下示例来分别介绍:

  1. 添加图片、文本到页眉页脚

  2. 设置奇/偶页页眉页脚不同

  3. 设置首页页眉页脚不同

  4. 添加页码(常规)

  5. 不连续添加页码

  6. 复制页眉页脚

  7. 锁定页眉页脚

  8. 删除页眉页脚

使用工具:Free Spire.Doc for .NET(免费版)

   注:下载安装该组件后,注意在你的VS项目程序中引用dll程序集文件(该dll文件可在安装文件下的Bin文件夹中获取),并在代码中添加程序所需的using指令。

【示例1】添加图片、文本到页眉页脚

using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using Spire.Doc.Fields; 
namespace AddHeaderAndFooter
{ 
   class Program 
      {   
         static void Main(string[] args)    
            {           
             //创建一个Document类实例,添加section和Paragraph            
             Document document = new Document(@"C:\Users\Administrator\Desktop\Test.docx");            
             Section sec = document.AddSection();            
             Paragraph para = sec.AddParagraph();             
             
             //声明一个HeaderFooter类对象,添加页眉、页脚            
             HeaderFooter header = sec.HeadersFooters.Header;            
             Paragraph headerPara = header.AddParagraph();            
             HeaderFooter footer = sec.HeadersFooters.Footer;            
             Paragraph footerPara = footer.AddParagraph();                       
             
             //添加图片和文本到页眉,并设置文本格式            
             DocPicture headerImage = headerPara.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\2.jpg"));            
             TextRange TR = headerPara.AppendText("The Word Trade Organization, WTO");            
             TR.CharacterFormat.FontName = "Andalus";            
             TR.CharacterFormat.FontSize = 12;            
             TR.CharacterFormat.TextColor = Color.Green;            
             TR.CharacterFormat.Bold = false;            
             headerImage.TextWrappingType = TextWrappingType.Right;             
             
             //添加文本到页脚,并设置格式            
             TR = footerPara.AppendText("The World Trade Organization is an intergovernmental organization that regulates international trade.The WTO officially commenced on 1 January 1995 under the Marrakesh Agreement, signed by 123 nations on 15 April 1994, replacing the General Agreement on Tariffs and Trade, which commenced in 1948. ");            
             TR.CharacterFormat.Bold = false;            
             TR.CharacterFormat.FontSize = 9;                       
             
             //保存文档并运行该文档            
             document.SaveToFile("图文页眉.docx", FileFormat.Docx);            
             System.Diagnostics.Process.Start("图文页眉.docx");        
             }   
        }
   }

页眉页脚添加效果:

https://img.mukewang.com/5d3016b10001d57907620413.jpg

【示例2】设置奇/偶页页眉页脚不同

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing; 

namespace HeadersFootersForOddAndEvenPages
{
    class Program 
       {    
           static void Main(string[] args)     
              {           
               //创建Document类,并加载测试文档            
               Document document = new Document();            
               document.LoadFromFile("test.docx");             
               
               //获取指定节,并设置页眉页脚奇偶页不同的属性为true            
               Section section = document.Sections[0];            
               section.PageSetup.DifferentOddAndEvenPagesHeaderFooter = true;             
               
               //设置奇偶数页的页脚            
               Paragraph P1 = section.HeadersFooters.EvenFooter.AddParagraph();            
               TextRange EF = P1.AppendText("偶数页页脚");            
               EF.CharacterFormat.FontName = "Calibri";            
               EF.CharacterFormat.FontSize = 12;            
               EF.CharacterFormat.TextColor = Color.Green;            
               EF.CharacterFormat.Bold = true;            
               P1.Format.HorizontalAlignment = HorizontalAlignment.Right;            
               Paragraph P2 = section.HeadersFooters.OddFooter.AddParagraph();            
               TextRange OF = P2.AppendText("奇数页页脚");            
               P2.Format.HorizontalAlignment = HorizontalAlignment.Left ;            
               OF.CharacterFormat.FontName = "Calibri";            
               OF.CharacterFormat.FontSize = 12;            
               OF.CharacterFormat.Bold = true;            
               OF.CharacterFormat.TextColor = Color.Blue;             
               
               //设置奇偶数页的页眉            
               Paragraph P3 = section.HeadersFooters.OddHeader.AddParagraph();            
               TextRange OH = P3.AppendText("奇数页页眉");            
               P3.Format.HorizontalAlignment = HorizontalAlignment.Left;            
               OH.CharacterFormat.FontName = "Calibri";            
               OH.CharacterFormat.FontSize = 12;            
               OH.CharacterFormat.Bold = true;            
               OH.CharacterFormat.TextColor = Color.Blue;            
               Paragraph P4 = section.HeadersFooters.EvenHeader.AddParagraph();            
               TextRange EH = P4.AppendText("偶数页页眉");            
               P4.Format.HorizontalAlignment = HorizontalAlignment.Right;            
               EH.CharacterFormat.FontName = "Calibri";            
               EH.CharacterFormat.FontSize = 12;            
               EH.CharacterFormat.Bold = true;            
               EH.CharacterFormat.TextColor = Color.Green;             
               
               //保存文档            
               document.SaveToFile("result.docx", FileFormat.Docx2010);            
               System.Diagnostics.Process.Start("result.docx");        
             }    
         }
     }

奇偶页页眉页脚设置效果:

https://img3.mukewang.com/5d3019fc0001778410330153.jpg

https://img2.mukewang.com/5d3019fc0001bbdc10370153.jpg


【示例3】设置首页页眉页脚不同

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing; 

namespace HeaderFootersDifferentFromFirstPage
{
    class Program 
       {     
          static void Main(string[] args)     
             {           
              //创建Document类的对象,并加载测试文档           
               Document document = new Document();            
               document.LoadFromFile("test.docx");             
               
               //获取指定节,并设置页眉页脚首页不同属性为true            
               Section section = document.Sections[0];            
               section.PageSetup.DifferentFirstPageHeaderFooter = true;             
               
               //加载图片添加到首页页眉            
               Paragraph paragraph1 = section.HeadersFooters.FirstPageHeader.AddParagraph();      
               paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Left;            
               DocPicture headerimage = paragraph1.AppendPicture(Image.FromFile("2.png"));    
               
               //添加文字到首页页脚            
               Paragraph paragraph2 = section.HeadersFooters.FirstPageFooter.AddParagraph();   
               paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Center;            
               TextRange FF = paragraph2.AppendText("首页页脚");            
               FF.CharacterFormat.FontSize = 12;             
               
               //添加页眉页脚到其他页面            
               Paragraph paragraph3 = section.HeadersFooters.Header.AddParagraph();            
               paragraph3.Format.HorizontalAlignment = HorizontalAlignment.Center;            
               TextRange NH = paragraph3.AppendText("非首页页眉");            
               NH.CharacterFormat.FontSize = 12;            
               Paragraph paragraph4 = section.HeadersFooters.Footer.AddParagraph();            
               paragraph4.Format.HorizontalAlignment = HorizontalAlignment.Center;            
               TextRange NF = paragraph4.AppendText("非首页页脚");            
               NF.CharacterFormat.FontSize = 12;             
               
               //保存文档            
               document.SaveToFile("result.docx", FileFormat.Docx2010);            
               System.Diagnostics.Process.Start("result.docx");        
             }   
         }
     }

首页页眉页脚设置效果:

https://img1.mukewang.com/5d301b4100014fb810940510.jpg


【示例4】添加页码(常规)

using Spire.Doc;
using Spire.Doc.Documents; 
namespace AddPageNumber_Doc
{
    class Program 
       {    
           static void Main(string[] args)    
               {            
                //实例化一个Document类,添加section和Paragraph           
                 Document document = new Document();            
                 Section sec = document.AddSection();            
                 Paragraph para = sec.AddParagraph();             
                 
                 //添加文本到paragraph,设置BreakType为分页            
                 para.AppendText("第1页");            
                 para.AppendBreak(BreakType.PageBreak);            
                 para.AppendText("第2页");             
                 
                 //创建一个HeaderFooter类实例,添加页脚            
                 HeaderFooter footer = sec.HeadersFooters.Footer;            
                 Paragraph footerPara = footer.AddParagraph();             
                 
                 //添加字段类型为页码,添加当前页、分隔线以及总页数            
                 footerPara.AppendField("页码", FieldType.FieldPage);            
                 footerPara.AppendText(" / ");            
                 footerPara.AppendField("总页数", FieldType.FieldNumPages);            
                 footerPara.Format.HorizontalAlignment = HorizontalAlignment.Right;             
                 
                 //保存文档            
                 document.SaveToFile("添加页码.docx", FileFormat.Docx);            
                 System.Diagnostics.Process.Start("添加页码.docx");        
               }    
          }
     }

常规页码设置下效果:

https://img2.mukewang.com/5d301c30000140b208370180.jpg


【示例5】不连续添加页码

using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing; 
namespace DifferentPageNumber_Doc

{
    class Program
        {   
            static void Main(string[] args)    
                {           
                 //创建Document对象,并加载测试文档            
                 Document doc = new Document();            
                 doc.LoadFromFile("test.docx");             
                 
                 //实例化HeaderFooter对象(指定页码添加位置:页眉或页脚)            
                 HeaderFooter footer = doc.Sections[0].HeadersFooters.Footer;            
                 
                 //添加段落到页脚            
                 Paragraph footerParagraph = footer.AddParagraph();            
                 
                 //添加页码域到页脚            
                 footerParagraph.AppendField("page number", FieldType.FieldPage);            
                 
                 //设置页码右对齐            
                 footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;  
                 //创建段落样式,包括字体名称、大小、颜色            
                 ParagraphStyle style = new ParagraphStyle(doc);            
                 style.CharacterFormat.Font = new Font("黑体", 10, FontStyle.Bold);            
                 style.CharacterFormat.TextColor = Color.Black;            
                 doc.Styles.Add(style);            
                 
                 //应用段落样式到页脚            
                 footerParagraph.ApplyStyle(style.Name);             
                 //将第一节的页码样式设置为罗马数字            
                 doc.Sections[0].PageSetup.PageNumberStyle = PageNumberStyle.RomanLower;     
                 
                 //将第二节的页码样式设置为阿拉伯数字,并重新开始编码            
                 doc.Sections[1].PageSetup.PageNumberStyle = PageNumberStyle.Arabic;            
                 doc.Sections[1].PageSetup.RestartPageNumbering = true;            
                 doc.Sections[1].PageSetup.PageStartingNumber = 1;//此处可任意指定起始页码数   
                 
                 //保存文档            
                 doc.SaveToFile("output.docx", FileFormat.Docx2010);            
                 System.Diagnostics.Process.Start("output.docx");        
              }    
         }
    }

页码添加效果:

https://img3.mukewang.com/5d301ce90001fb5b11660480.jpg

【示例6】复制页眉页脚

using Spire.Doc; 

namespace CopyHeaderAndFooter_Doc
{
    class Program 
       {    
           static void Main(string[] args)    
               {           
                //新建Word文档1,并加载带页眉的源文档           
                 Document doc1 = new Document();            
                 doc1.LoadFromFile("test1.docx");             
                 
                 //获取文档1的页眉            
                 HeaderFooter Header = doc1.Sections[0].HeadersFooters.Header;             
                 
                 //新建文档2,并加载目标文档            
                 Document doc2 = new Document("test2.docx");             
                 //遍历文档2中的所有Section            
                 foreach (Section section in doc2.Sections)            
                   {              
                      foreach (DocumentObject obj in Header.ChildObjects)              
                        {                    
                         //将复制的页眉对象添加到section                    
                         section.HeadersFooters.Header.ChildObjects.Add(obj.Clone());   
                         }           
                    }             
                  
                  //保存并打开文档            
                  doc2.SaveToFile("copyHeader.docx", FileFormat.Docx2013);            
                  System.Diagnostics.Process.Start("copyHeader.docx");        
                }              
            }
       }


【示例7】锁定页眉页脚

using Spire.Doc; 

namespace ProtectHeaderFooter_Doc
{ 
   class Program 
      {     
         static void Main(string[] args)     
            {           
             //加载测试文档            
             Document doc = new Document();            
             doc.LoadFromFile("sample.docx");             
             
             //获取第一个section            
             Section section = doc.Sections[0];             
             //保护文档并设置 ProtectionType 为 AllowOnlyFormFields,并设置启用编辑的密码    
             doc.Protect(ProtectionType.AllowOnlyFormFields, "123");             
             
             //设置ProtectForm 为false 允许编辑其他区域            
             section.ProtectForm = false;             
             
             //保存文档            
             doc.SaveToFile("result.docx", FileFormat.Docx2013);            
             System.Diagnostics.Process.Start("result.docx");        
           }    
       }
   }

运行程序后生成的文档,页眉将不允许被编辑,正确输入密码后,方可编辑页眉。

https://img.mukewang.com/5d301e2f00013e2d11700716.jpg


【示例8】删除页眉页脚

   1.删除所有页面的页眉页脚

using Spire.Doc; 
namespace RemoveHeaderFooter_Doc
{ 
    class Program
        {    
            static void Main(string[] args)    
                {           
                 //创建一个Document实例并加载示例文档            
                 Document doc = new Document();            
                 doc.LoadFromFile("sample.docx");            
                 
                 //获取第一个section            
                 Section section = doc.Sections[0];             
                 
                 //删除页眉            
                 section.HeadersFooters.Header.ChildObjects.Clear();             
                 //删除页脚            
                 section.HeadersFooters.Footer.ChildObjects.Clear();             
                 
                 //保存文档            
                 doc.SaveToFile("result.docx", FileFormat.Docx);            
                 System.Diagnostics.Process.Start("result.docx");        
               }    
           }
      }

 2. 删除首页的页眉页脚(适用于文档封面,不需要页眉页脚的情况,或者其他情形)

using Spire.Doc; 

namespace RemoveHeaderFooter2_Doc
{
    class Program 
       {     
          static void Main(string[] args)     
             {           
              //创建一个Document实例并加载示例文档            
              Document doc = new Document();            
              doc.LoadFromFile("sample.docx");             
              
              //获取第一个section            
              Section section = doc.Sections[0];             
              //设置页眉页脚首页不同            
              section.PageSetup.DifferentFirstPageHeaderFooter = true;             
              
              //删除首页页眉页脚            
              section.HeadersFooters.FirstPageHeader.ChildObjects.Clear();             
              
              //保存文档            
              doc.SaveToFile("output.docx", FileFormat.Docx);            
              System.Diagnostics.Process.Start("output.docx");        
             }    
         }
    }


(本文完)

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP