从Word.Range读取页眉和页脚 - VSTO Word Interop C#

时间:2010-07-20 14:52:37

标签: c# interop ms-word vsto

我有一个Range对象,我想用它来从Range所在的页面中提取信息。信息位于表格中的页眉和页脚中,我想要阅读表格中的文字。

我试过了:word.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Shapes.Range(ref pageNumber).TextFrame.TextRange.Text;

其中单词是RangepageNumber是此范围所在的页码。 问题是我无法获得真正的页码!使用word.get_information(WdInformation.wdActiveEndPageNumber)返回错误的页码!

2 个答案:

答案 0 :(得分:6)

我找到了任何有兴趣的答案:

int i = (int)range.get_Information(WdInformation.wdActiveEndPageNumber) % 2;
WdHeaderFooterIndex index;
if (i == 0 && range.Sections[1].PageSetup.OddAndEvenPagesHeaderFooter == 1)
    index = WdHeaderFooterIndex.wdHeaderFooterEvenPages;
else
    index = WdHeaderFooterIndex.wdHeaderFooterPrimary;

Range sRange = range.Sections[1].Range;
object direction = Word.WdCollapseDirection.wdCollapseStart;
sRange.Collapse(ref direction);
if (range.get_Information(WdInformation.wdActiveEndPageNumber) == sRange.get_Information(WdInformation.wdActiveEndPageNumber)
    && range.Sections[1].PageSetup.DifferentFirstPageHeaderFooter == 1)
    index = WdHeaderFooterIndex.wdHeaderFooterFirstPage;

object rangeIndex = 1;
Range headerRange = range.Sections[1].Headers[index].Range.ShapeRange.TextFrame.TextRange;

string profession = headerRange.Tables[1].Cell(4, 1).Range.Text;
string manPower = headerRange.Tables[1].Cell(4, 2).Range.Text;
string registration = headerRange.Tables[1].Cell(4, 3).Range.Text;
string taggingListNum = headerRange.Tables[1].Cell(4, 4).Range.Text;

答案 1 :(得分:0)

读取所有文本文档。随后,我用它来分析和提取数据:

        Document doc = Globals.ThisAddIn.Application.ActiveDocument; 

        string headers = "";

        foreach (Section section in doc.Sections)
        {
            foreach (HeaderFooter hf in section.Headers)
            {
                headers += hf.Range.Text;
            }
        }

        string docText = headers + doc.Range(doc.Content.Start, doc.Content.End).Text;