How to add items one at a time to to a new line a word document using word interop

sixshift04 picture sixshift04 · Oct 4, 2012 · Viewed 24.5k times · Source

I am trying to add these three types of content into a word doc. This is how I am trying to do it now. However, each item replaces the last one. Adding images always adds to the beginning of the page. I have a loop that calls a function to create the headers and tables, and then adds images after. I think the problem is ranges. I use a starting range of object start = 0;

How can I get these to add one at a time to to a new line in the document?

foreach (var category in observedColumns)
            {

                CreateHeadersAndTables();
                createPictures();
            }

Adding Headers:

                object start = 0;
                Word.Range rng = doc.Range(ref start , Missing.Value);
                Word.Paragraph heading;
                heading = doc.Content.Paragraphs.Add(Missing.Value);
                heading.Range.Text = category;
                heading.Range.InsertParagraphAfter();

Adding Tables:

            Word.Table table;
            table = doc.Content.Tables.Add(rng, 1, 5);

Adding Pictures:

            doc.Application.Selection.InlineShapes.AddPicture(@path);

Answer

Lasse Christiansen picture Lasse Christiansen · Oct 5, 2012

A simple approach will be using paragraphs to handle the Range objects and simply insert a new paragraph one by one.

Looking at the API documentation reveals that Paragraphs implements an Add method which:

Returns a Paragraph object that represents a new, blank paragraph added to a document. (...) If Range isn't specified, the new paragraph is added after the selection or range or at the end of the document.

Source: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.paragraphs.add(v=office.14).aspx

In that way, it gets straight forward to append new content to the document.

For completeness I have included a sample that shows how a solution might work. The sample loops through a for loop, and for each iteration it inserts:

  • A new line of text
  • A table
  • A picture

The sample has is implemented as a C# console application using:

  • .NET 4.5
  • Microsoft Office Object Library version 15.0, and
  • Microsoft Word Object Library version 15.0

... that is, the MS Word Interop API that ships with MS Office 2013.

using System;
using System.IO;
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;

namespace StackOverflowWordInterop
{
    class Program
    {
        static void Main()
        {
            // Open word and a docx file
            var wordApplication = new Application() { Visible = true };
            var document = wordApplication.Documents.Open(@"C:\Users\myUserName\Documents\document.docx", Visible: true);

            // "10" is chosen by random - select a value that fits your purpose
            for (var i = 0; i < 10; i++)
            {
                // Insert text
                var pText = document.Paragraphs.Add();
                pText.Format.SpaceAfter = 10f;
                pText.Range.Text = String.Format("This is line #{0}", i);
                pText.Range.InsertParagraphAfter();

                // Insert table
                var pTable = document.Paragraphs.Add();
                pTable.Format.SpaceAfter = 10f;
                var table = document.Tables.Add(pTable.Range, 2, 3, WdDefaultTableBehavior.wdWord9TableBehavior);
                for (var r = 1; r <= table.Rows.Count; r++)
                    for (var c = 1; c <= table.Columns.Count; c++)
                        table.Cell(r, c).Range.Text = String.Format("This is cell {0} in table #{1}", String.Format("({0},{1})", r,c) , i);

                // Insert picture
                var pPicture = document.Paragraphs.Add();
                pPicture.Format.SpaceAfter = 10f;
                document.InlineShapes.AddPicture(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "img_1.png"), Range: pPicture.Range);

            }

            // Some console ascii-UI
            Console.WriteLine("Press any key to save document and close word..");
            Console.ReadLine();

            // Save settings
            document.Save();

            // Close word
            wordApplication.Quit();
        }
    }
}