alexay68
alexay68

Reputation: 172

c# how to get tables in the footer of a word document

I got some problems with the Microsoft office library in C#. When I try to get the table present in my first page's footer, the programme cannot find it, I can only get the table in text format :

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();

Thanks for your attention

EDIT : exception :

enter image description here

It says : "Member of required collection does not exists"

Upvotes: 0

Views: 1540

Answers (1)

Dirk Vollmar
Dirk Vollmar

Reputation: 176229

If your section is setup to feature a different first page header/footer, you would need to get that particular first page footer using wdHeaderFooterFirstPage:

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

If you don't know the section/page setup of your document, you can get the range of the footer that appears on the first page as follows:

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

Note that the table index starts at 1 (something already mentioned in the comments), so that you will need to adjust your code to Table t = range.Tables[1];


Note that you can make your code a lot more readable by importing namespaces with using directives at the top of your file, by omitting optional parameters, and by removing the explicit object declarations (the latter things were required only in early versions of .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();

Upvotes: 1

Related Questions