MS Word Automation - 查找表所在的页码

时间:2017-01-09 06:15:05

标签: c# ms-word automation office-interop

我有一个包含10个表的Word文档。当我读取这些表中的值时,我想向操作员发出警告,以检查第5页的表4。 我可以得到表号,但有没有办法表明该表是哪个页面?我的代码片段如下:

int nTable = 0;
int nPage = 0;
foreach (Word.Table tb in doc.Tables)
{
  nTable++;
  nPage = PageNumberForTable(nTable); // I need a function like this
  numRows = tb.Rows.Count;
  numColumns = tb.Columns.Count;

  for (int row = 1; row <= numRows; row++) 
  {
    for(int col = 1; col <= numColumns; col++) 
    {
        var cell = tb.Cell(row, col); 
        cellValue = CleanRASpace(cell.Range.Text); 
        if(cellValue == 2) 
        {
           MessageBox.Show("Check table " + nTable + " on page " + nPage);
        }
    }
  }
}

1 个答案:

答案 0 :(得分:2)

您可以获取表格所用的页码:

table.Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber];

当你说你需要像以下这样的功能时:

nPage = PageNumberForTable(nTable);

看起来很奇怪......我认为你可能需要两种方法,一种是从名称(Title)获取另一种方法来获取给定页面上的所有表格。为了获取给定页面上的表格,我使用了一个列表来保存它们,因为该页面上可能有多个表格。在单词文档中,我将表Titles设置为table1,table2,table3 ......等等。此外,如果表拆分页面,它将返回表结束的页面。希望这会有所帮助。

private static int GetTablePageNumberFromTitle(string inTitle, Word.Document doc) {
  foreach (Word.Table tb in doc.Tables) {
    if (tb.Title == inTitle) {
      return tb.Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber]; 
    }
  }
  return -1;
}

private static List<Word.Table> GetTablesOnPage(int targetPage, Word.Document doc) {
  List<Word.Table> tablesOnPage = new List<Word.Table>();
  int curPage = -1;
  foreach (Word.Table tb in doc.Tables) {
    curPage = tb.Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber];
    if (curPage == targetPage) {
      tablesOnPage.Add(tb);
    }
  }
  return tablesOnPage;
}

一些测试

  Console.WriteLine("--------------");
  Console.WriteLine("Get page table named 'table3' is on...");
  int pageNum = GetTablePageNumberFromTitle("table3", doc);
  Console.WriteLine("'table3 is on page: " + pageNum);
  Console.WriteLine("--------------");
  Console.WriteLine("Get page table named 'table2' is on... It starts on page 2 and ends on page 3");
  pageNum = GetTablePageNumberFromTitle("table2", doc);
  Console.WriteLine("'table2 is on page: " + pageNum);
  Console.WriteLine("--------------");
  Console.WriteLine("Get tables on page 4");
  List<Word.Table> allTables = GetTablesOnPage(4, doc);
  foreach (Word.Table tb in allTables) {
    Console.WriteLine(tb.Title + " is on page " + 4);
  }
  Console.WriteLine("--------------");
  Console.WriteLine("Get tables on page 5");
  allTables = GetTablesOnPage(5, doc);
  foreach (Word.Table tb in allTables) {
    Console.WriteLine(tb.Title + " is on page " + 5);
  }