I am exporting data from a database to a word document in WinForms using C#
The resultant document has 5 Sections due to using:
Range.InsertBreak(WdBreakType.wdSectionBreakNextPage);
What i wish to know is, how do i refer to each section individually - so i can set a different header for each section, instead of doing this:
foreach (Section section in aDoc.Sections)
{
//Get the header range and add the header details.
var headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
headerRange.Fields.Add(headerRange, WdFieldType.wdFieldPage);
headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
headerRange.Font.ColorIndex = WdColorIndex.wdBlack;
headerRange.Font.Size = 14;
headerRange.Font.Name = "Arial";
headerRange.Font.Bold = 1;
headerRange.Text = Some Header Here;
headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
}
Because this sets every header to "Some Header Here"
By default, when new sections are generated in a Word document, the property LinkToPrevious
is set to True. This means that the new section "inherits" the headers and footers of the previous section.
In order to have different header/footer content in each section, it's necessary to set LinkToPrevious
to False. This can be done as you create the sections, or at any time after that, but it should be done before you write content to a header/footer. If the link is broken after the header/footer contains content, that content will be lost (but does remain in the "parent" header/footer to which the section was linked).
So to address an individual Section, remove the link, and write content to its Header you can:
Word.Section sec = doc.Sections[indexValue]
Word.HeaderFooter hf = sec.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
hf.LinkToPrevious = false;
hf.Range.Text = "Content for this header";
Note: There is no need to write the sections to a List in order to give them different content.