c#操作word设置页眉页脚,页脚同时包括文字和页码
(2013-09-06 10:19:56)一、页眉
通过插入分节符下一页,将文档分为几节。
object oSectionBreak=WdBreakType.wdSectionBreakNextPage;
WordApp.Selection.Range.InsertBreak(ref oSectionBreak);
给不同的节附不同的页眉
本文将文档分为6节,1、3、5节没有页眉,2、4、6节页眉内容各不相同。
WordDoc.ActiveWindow.View.SeekView =
WdSeekView.wdSeekPrimaryHeader;
Range allRange = WordDoc.Range(ref m_oMissing, ref
m_oMissing);
foreach (Section section in allRange.Sections)
{
//各节均不链接前一节
//页眉居中
//设置页眉的字体
//sections[]的编号从1开始
//设置1、3、5节页眉没有横线
allRange.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;
allRange.Sections[3].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle
= WdLineStyle.wdLineStyleNone;
allRange.Sections[5].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle
= WdLineStyle.wdLineStyleNone;
//设置2、4、6节页眉内容且有横线
allRange.Sections[2].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle
= WdLineStyle.wdLineStyleSingle;
allRange.Sections[2].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text
="第2节";
allRange.Sections[4].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle
= WdLineStyle.wdLineStyleSingle;
allRange.Sections[4].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text
= "第4节";
allRange.Sections[6].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle
= WdLineStyle.wdLineStyleSingle;
allRange.Sections[6].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text
= "第6节";
//从页眉页脚设计模式返回主文档
WordDoc.ActiveWindow.View.SeekView =
WdSeekView.wdSeekMainDocument;
二、页脚
1、3、5节没有页脚,2、4、6节有页脚,且页脚包括文字和页码,文字居中,页码右对齐
{
//页脚文字居中
//页脚文字字体
//设置2、4、6节页脚文字,和页码
//注意前后顺序,要先写入文字,再写入页码,若反过来则页码被文字覆盖掉
allRange.Sections[2].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text
= "第2节";
allRange.Sections[2].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add(ref
oNumberAlignment, ref oFirstPage);
allRange.Sections[4].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text
= "第4节";
allRange.Sections[4].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add(ref
oNumberAlignment, ref oFirstPage);
allRange.Sections[6].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text
= "第6节";
allRange.Sections[6].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add(ref
oNumberAlignment, ref oFirstPage);
WordDoc.ActiveWindow.View.SeekView =
WdSeekView.wdSeekMainDocument;