![](/img/trans.png)
[英]C# MS Word: How to get page number where a table cell starts and where it ends?
[英]MS Word Automation - find the page number where a table is located
我有一個包含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);
}
}
}
}
您可以獲取表格所在的頁碼:
table.Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber];
當您說您需要一個類似的功能時:
nPage = PageNumberForTable(nTable);
似乎很奇怪……我想您可能需要兩種方法,一種方法是從名稱(標題)獲取表,另一種方法獲取給定頁面上的所有表。 為了獲得給定頁面上的表,我使用了一個列表來保存它們,因為該頁面上可能有多個表。 在單詞document中,我將表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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.