Word Headings generated in C#

D

Daniel

Hi I'm creating an application that generates a report in Word 2003. Using C#

My problem is that I need headings to create a table of content, so I search
the web trying to find a way to do this.

My solution was something like this:

using Word = Microsoft.Office.Interop.Word;
using System.Reflection;

object oMissing = System.Reflection.Missing.Value;
Word._Document oDoc;


public void Header1(String s)
{
object oStyle = Word.WdBuiltinStyle.wdStyleHeading1;
Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.set_Style(ref oStyle);
oPara1.Range.Text = s;
oPara1.Range.InsertParagraphAfter();
}

The problem is that is looks like a Heading1 but it isn't a heading.
 
R

Rob

It doesn't look like you're actually setting the style. What is oStyle and
where is it defined/initialized? In VBA it would look something like this:

ActiveDocument.Paragraphs(1).Style = ActiveDocument.Styles("Heading 1")

Maybe you can find some similar method/property to set. ActiveDocument
should be the same as your oDoc.
 
D

Daniel

I solved it.
The answer was to name the predefined style in a word template.

Something like this:

using Word = Microsoft.Office.Interop.Word;
using System.Reflection;

Word._Application oWord = new Word.Application();

object oMissing = System.Reflection.Missing.Value;
Word._Document oDoc;

/* Get the template and use it in the document */
object oTemplate = "C:\\Template.dot";
oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref
oMissing);

/* Define oHeading1 */
object oHeading1 = "HeadingName";

public void Heading1(String s)
{
Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = s;
oPara1.Range.set_Style(ref oHeading1);
oPara1.Range.InsertParagraphAfter();
LineBreake();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top