2017-09-15 61 views
0

我在C#中的Microsoft office庫中遇到了一些問題。當我試圖讓本表在我的第一頁的頁腳,程序無法找到它,我只能拿到表中的文本格式:c#如何在word文檔的頁腳中獲取表格

object nom_fi = (object)chemin; 
object readOnly = false; 
object isVisible = false; 
object missing = System.Reflection.Missing.Value; 
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); 
Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref nom_fi, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); 
doc.Activate(); 

foreach (Microsoft.Office.Interop.Word.Section sec in doc.Sections) 
{ 
    Microsoft.Office.Interop.Word.Range range = sec.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; 
    Microsoft.Office.Interop.Word.Table t = range.Tables[0]; 
} 
doc.Close(); 

感謝您的關注

編輯:異常:

enter image description here

它說:「需要收集的成員不存在」

+0

你是什麼意思「程序找不到它,我只能以文本格式獲取表格」? – STORM

+0

我有個例外: – alexay68

+0

我可以得到range.Text,它返回由\ t \和其他分隔的頁腳字段,但是range.Tables [0]返回異常 – alexay68

回答

1

如果你的部分是設置到f eature不同的第一頁頁眉/頁腳,您將需要使用wdHeaderFooterFirstPage獲得特定的第一頁的頁腳:

Range range = sec.Footers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range; 

如果你不知道你的文檔的部分/頁面設置,你可以得到的範圍

Range range; 
if (sec.Footers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Exists) 
{ 
    range = sec.Footers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range; 
} 
else 
{ 
    range = sec.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; 
} 

注意到,該表的索引從1開始,(一些已經在評論中提到的),這樣你就需要調整您的代碼以Table t = range.Tables[1];


:即如下的第一頁上顯示的頁腳

請注意,通過刪除文件頂部的using指令,通過省略可選參數以及刪除明確的object聲明(後者僅在早期版本的版本中才需要),可以使代碼更具可讀性。 .NET):

using Microsoft.Office.Interop.Word; 

var wordApp = new Application(); 
var doc = wordApp.Documents.Open(chemin, ReadOnly: false, Visible: false); 
doc.Activate(); 

foreach (Section sec in doc.Sections) 
{ 
    var range = sec.Footers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range; 
    var table = range.Tables[1]; 
} 

doc.Close(); 
+0

問題出在索引從1開始。我知道我應該使用「using」指令,但我已經使用System.Data.DataTable並且發生了一些衝突 – alexay68

+0

@ alexay68:在評論中你說問題不是索引,因此我的答案是。關於'using'指令:你總是可以使用一個命名的導入,例如'使用Word = Microsoft.Office.Interop.Word;'然後在代碼中使用該名稱,例如'var wordApp = new Word.Application();' –

+0

問題是部分順便說一句迭代...我需要得到部分[1],而不是做一個foreach(foreach並不重要,因爲文檔總是相同的頁腳結構獲得ISO 9001標準) – alexay68