Reputation: 1362
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"
Upvotes: 0
Views: 2719
Reputation: 25663
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.
Upvotes: 1
Reputation: 3280
Since Sections
property is just an untyped IEnumerable, you can do the following to make a typed list of sections from it. Notice that you need to import System.Linq
and System.Collections.Generic
namespaces for this to work.
List<Section> sections = new List<Section>(aDoc.Sections.Cast<Sections>());
Now, if you need to set specific section's header, you can write
Section section1 = sections[0];
var section1HeaderRange = section1.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
section1HeaderRange.Text = "Section 1 Header";
Section section2 = sections[1];
var section2HeaderRange = section2.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
section2HeaderRange.Text = "Section 2 Header";
Upvotes: 0