Saturday, May 15, 2010

Some Simple Code Snippet for Vsto 2007 (Word)

While Learning Vsto With Word I have came Some simple Code snippet which may come handy.
When The Real programming Begins ..

Requirment :-

Interest with
Vs2008
and Vsto

Let Start

1} Inserting Text in Word 2007


InsertAfter method inserts text at the end of the active range or selection, whereas InsertBefore inserts text at the start of the active range or selection.

Code :-

// Using InsertBefore method inserts text
this.Application.ActiveDocument.Content.InsertBefore("Avinash @ The Start-");

//using Insert method insert text
this.Application.ActiveDocument.Content.InsertAfter(" - Avinash @ the End ");

Same Opertion Can be Performed using Selection Object

// Using Selection Object inserting text after the text
this.Application.Selection.InsertAfter("Avinash @ The End");

// Using Selection Object inserting text before the text

this.Application.Selection.InsertBefore("Avinash @ The Start");

2} Selecting text in a Word 2007 document


///Intializing the range object
Word.Range PackRangeSelect;
////check the sentence count
if (this.Sentences.Count >= 1)
{
////set the start and end point has object
object pktStartfrom = this.Sentences[2].Start;
object pktStopHere = this.Sentences[5].End;
////assign the selection range
PackRangeSelect = this.Range(ref pktStartfrom, ref pktStopHere);

////select the sentence using select() Method
PackRangeSelect.Select();
}
else
{
return;
}

OutPut



3} Creating Table in Word



//Object instance
object pktMissing = System.Type.Missing;

// Range on the application selection

Word.Range PacktRangePresent = this.Application.Selection.Range;

// Using Table object add in the Word document

Word.Table PacktTable = this.Application.ActiveDocument.Tables.Add(PacktRangePresent, 3, 4, ref pktMissing, ref pktMissing);

// Border propety of the Table we are creating

Word.Border[] PacktBorder = new Word.Border[6];
PacktBorder[0] = PacktTable.Borders[Word.WdBorderType.wdBorderLeft];
PacktBorder[1] = PacktTable.Borders[Word.WdBorderType.wdBorderRight];
PacktBorder[2] = PacktTable.Borders[Word.WdBorderType.wdBorderTop];
PacktBorder[3] = PacktTable.Borders[Word.WdBorderType.wdBorderBottom];
PacktBorder[4] = PacktTable.Borders[Word.WdBorderType.wdBorderHorizontal];
PacktBorder[5] = PacktTable.Borders[Word.WdBorderType.wdBorderVertical];
// Border formatting of the Table
// Loop through the border and set color for table
foreach (Word.Border pktBorder in PacktBorder)
{
// Table line style propety
pktBorder.LineStyle = Word.WdLineStyle.wdLineStyleTriple;
// Table line color property
pktBorder.Color = Word.WdColor.wdColorGray30;
}

Output:-

No comments:

Post a Comment