Add Images, Styles, Tables to Microsoft Office Word in C#


In this article we will code How to add Tables to a Microsoft Office Word document and adding images and styles for it.

  1. Add Reference of “ Microsoft.Office.Interop.Word;” into your project

  2. In the page load write the following code.

The method looks like as follows:

 

 

using System;

using Microsoft.Office.Interop.Word;

 

 

public partial class _Default : System.Web.UI.Page

{

  

    protected void Page_Load(object sender, EventArgs e)

    {

        //InsertImage();

       InsertTable();

    }

   

    public void InsertTable()

    {

        Microsoft.Office.Interop.Word.Document WordDoc;

        Microsoft.Office.Interop.Word.ApplicationClass oWordApplic = new ApplicationClass();

       

        Microsoft.Office.Interop.Word.Table axTable;

        Microsoft.Office.Interop.Word.Application axWord;

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

        axWord.Visible = true;

 

        WordDoc = axWord.Documents.Open("D:\\MyTemplate.doc");

        axTable = WordDoc.Tables.Add(axWord.Selection.Range, 5, 3);

       

        // Show Borders

        axTable.Range.Columns.Borders.Enable.ToString();

       

        axTable.set_Style("Table Grid 8");

        // This is For Header columns

        axTable.Cell(1, 1).Range.Text = "Employee Name";

        axTable.Cell(1, 2).Range.Text = "Country Image";

        axTable.Cell(1, 3).Range.Text = "Passport Number";

 

        axTable.Cell(2, 1).Range.Text = "Siva";

       

        Range rngPic1 = WordDoc.Tables[1].Cell(2, 2).Range;

        object missing = System.Reflection.Missing.Value;       

        rngPic1.InlineShapes.AddPicture(@"d:\India.jpg", ref missing, ref missing, ref missing);

 

        axTable.Cell(2, 3).Range.Text = "A123456";

 

        axTable.Cell(3, 1).Range.Text = "Raj";

        Range rngPic2 = WordDoc.Tables[1].Cell(3, 2).Range;

        rngPic2.InlineShapes.AddPicture(@"d:\sydney.png", ref missing, ref missing, ref missing);

        axTable.Cell(3, 3).Range.Text = "B123456";

 

        axTable.Cell(4, 1).Range.Text = "Babu";

        Range rngPic = WordDoc.Tables[1].Cell(4, 2).Range;

       

        //Range rngPic = rng.Tables[1].Cell(2, 3).Range;

        rngPic.InlineShapes.AddPicture(@"d:\USA.jpg", ref missing, ref missing, ref missing);

        axTable.Cell(4, 3).Range.Text = "USA123456";

 

       

    

    }

}

 

 

 

 

After Running it, the Microsoft Office Word document will be opened and executes and displays the following output.

Note: Please add some sample (three) images to your specified drive. In this code I have given the following path:

  

Output: