, , ,

Every developer is able to create Excel extensions using Visual Studio, as it is offering a special kind of project for this, called “Word 2013 Add-in”. Unfortunately this is not very popular so you might show some interest in this article for situations when you are required to do this and you are not able to find too much on the internet. The article will show how to insert in the header a table with one row and two columns. In the first column we will insert a text and in the other we will insert a picture..

Before start building the code, just add an image (in my case is called “Logo.jpg”) to the project as a resource. Once you are done with this, set the “Copy to Output Directory” property for this image to “Copy always”. We need this because we need a location of the file to be able to insert it into the document.

Second step is to get the header of the document.

foreach(Section section in Globals.ThisAddIn.Application.ActiveDocument.Sections)
    Range header = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;

    // The rest of the code will be here

Now is the time to add table to the header and set width to 100%

 Table tblHeader = header.Tables.Add(header, 1, 2, Type.Missing, Type.Missing);
 tblHeader.PreferredWidth = 100;
 tblHeader.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;

In the first cell, we will write a text, set vertical alignment to center and horizontal one to left.

tblHeader.Cell(1, 1).Range.Text = "Here can be company name";
tblHeader.Cell(1, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
tblHeader.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;

In the second cell we will add an image to the right and vertically centered.

string directory = System.IO.Path.GetDirectoryName(ApplicationDeployment.CurrentDeployment.UpdateLocation.AbsoluteUri);
string logoPath =  directory +  @"\Resources" + @"\logo.jpg";
tblHeader.Cell(1, 2).Range.InlineShapes.AddPicture(logoPath, Type.Missing, Type.Missing, Type.Missing);
tblHeader.Cell(1, 2).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
tblHeader.Cell(1, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;

Please note how we obtain the location of our picture. We cannot add directly from resources, but we can copy to output directory and obtain path to it.

Happy Coding!