2017-09-15 115 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