从Word文档的n页开始在页脚中添加页码

时间:2018-10-31 23:26:51

标签: c# ms-word office-interop

我需要从字文档的第5页开始添加页码(X的第1页)。怎么做。我添加到整个文档中的代码,我无法控制它。 我在C#中使用Word互操作。 请帮忙。

 oDoc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;
                        //Object oMissing = System.Reflection.Missing.Value;
                        oDoc.ActiveWindow.Selection.TypeText("\t Page ");
                        Object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages;
                        Object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
                        oDoc.ActiveWindow.Selection.HeaderFooter.LinkToPrevious = false;
                        oDoc.ActiveWindow.Selection.Fields.Add(oDoc.ActiveWindow.Selection.Range, ref CurrentPage, ref oMissing, ref oMissing);
                        oDoc.ActiveWindow.Selection.TypeText(" of ");
                        oDoc.ActiveWindow.Selection.Fields.Add(oDoc.ActiveWindow.Selection.Range, ref TotalPages, ref oMissing, ref oMissing);
                       

1 个答案:

答案 0 :(得分:1)

为了(重新)开始在文档中编号,需要分节符。下面的示例演示了如何在目标页之前插入“下一页”分节符,然后格式化新节的页脚以进行页码编号,以该节中的1开始。

请注意,我还根据总页数应该是新部分而不是整个文档的总页数,将分配更改为TotalPages

        //Go to page where page numbering should start
        string pageNum = "3";
        wdApp.Selection.GoTo(Word.WdGoToItem.wdGoToPage, Word.WdGoToDirection.wdGoToNext, ref missing, pageNum);
        Word.Range rngPageNum = wdApp.Selection.Range;
        //Insert Next Page section break so that numbering can start at 1
        rngPageNum.InsertBreak(Word.WdBreakType.wdSectionBreakNextPage);

        Word.Section currSec = doc.Sections[rngPageNum.Sections[1].Index];
        Word.HeaderFooter ftr = currSec.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];

        //So that the footer content doesn't propagate to the previous section    
        ftr.LinkToPrevious = false;
        ftr.PageNumbers.RestartNumberingAtSection = true;
        ftr.PageNumbers.StartingNumber = 1;

        //If the total pages should not be the total in the document, just the section
        //use the field SectionPages instead of NumPages
        object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldSectionPages;
        object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
        Word.Range rngCurrSecFooter = ftr.Range;
        rngCurrSecFooter.Fields.Add(rngCurrSecFooter, ref CurrentPage, ref missing, false);
        rngCurrSecFooter.InsertAfter(" of ");
        rngCurrSecFooter.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
        rngCurrSecFooter.Fields.Add(rngCurrSecFooter, ref TotalPages, ref missing, false);