Autmating Word Document with Tables and Table of Contents

D

Doug

I am having a terrible time trying to get a word document automated using C#
and Microsoft.Office.Interop.Word 12.0. Here is my code so far followed by
what I expect the code to spit out.


public void createWordDocAppP(int pid)
{
object varFileName = "c:\\temp\\temp.doc";
object varFalseValue = false;
object varTrueValue = true;
object varMissing = Type.Missing;
object styleHeading = "Heading 1";
object page = WdBreakType.wdPageBreak;

Microsoft.Office.Interop.Word.Application varWord = new
Microsoft.Office.Interop.Word.Application();

Document varDoc = varWord.Documents.Add(ref varMissing, ref
varMissing, ref varMissing, ref varTrueValue);

varDoc.Activate();

this.toolStripStatusLabel1.Text = "";
this.toolStripStatusLabel1.Invalidate();
this.repStatusStrip.Update();

object start = 0;
object end = 0;
object oEndOfDoc = "\\endofdoc";
object oStyleHeading = varDoc.Styles.get_Item(ref styleHeading);
int n = 0;

varDoc.Paragraphs.LineUnitAfter = 1;
rng.Font.Name = "Times New Roman";

Range rngTocTitle = varDoc.Bookmarks.get_Item(ref
oEndOfDoc).Range;
//Insert a Table of contents into the Document
rngTocTitle.Paragraphs[1].Alignment =
WdParagraphAlignment.wdAlignParagraphCenter;
rngTocTitle.Font.Size = 12;
rngTocTitle.Font.Bold = 1;
rngTocTitle.Text = "Table of Contents";

Range rngToc = varDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
rngToc.Paragraphs[1].Alignment =
WdParagraphAlignment.wdAlignParagraphLeft;
TableOfContents toc = varDoc.TablesOfContents.Add(rngToc, ref
varTrueValue, ref varMissing, ref varMissing, ref varMissing, ref varMissing,
ref varTrueValue, ref varTrueValue, ref varTrueValue, ref varTrueValue, ref
varTrueValue, ref varTrueValue);
rngToc.InsertParagraphBefore();

Range pgBreak = varDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
pgBreak.InsertBreak(ref page);

Range rngSect1 = varDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
rngSect1.Font.Size = 12;
rngSect1.Font.Bold = 1;
rngSect1.Paragraphs.OutlineLevel = WdOutlineLevel.wdOutlineLevel1;
rngSect1.Text = "P.1\tSection 1";

//TODO: Insert Table followed by Page Break

toc.Update();

Why is the "Table of Contents" not Bold or Centered on the page? Why is the
rngSect1.Text not Bold as well? I understand my problem most likely has to
do with the range I am using, but I have tried several different
configurations to no avail. Can anyone help me out here?
 
M

MacDermott

Without having studied your code extensively, I'd comment that a great way
to generate code for automation is to first open Word manually and record a
macro as you step through the keystrokes you want to capture.
You can then use that macro as a guide to your coding.

HTH
- Turtle
 

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