Add a row to an MS Word table using Office.Interop

Our Man in Bananas picture Our Man in Bananas · Dec 18, 2013 · Viewed 13k times · Source

I have a word template with a table that I am populating from a list of strings that I split using tab characters.

I do not know how many lines of text I will have as it will vary.

So I am adding a row programmatically before iterating through my loop like this:

oWordDoc.Tables[2].Rows.Add(oWordDoc.Tables[2].Rows[1]);

Unfortunately it is adding the row before rather than after the current row.

How can I change my code to always have an empty row added after the current row?

Answer

joecop picture joecop · Dec 20, 2013

Leave the parameter value as a missing value for the Row.Add Function

object oMissing = System.Reflection.Missing.Value;        
// get your table or create a new one like this
// you can start with two rows. 
Microsoft.Office.Interop.Word.Table myTable = oWordDoc.Add(myRange, 2,numberOfColumns)
int rowCount = 2; 
//add a row for each item in a collection.
foreach( string s in collectionOfStrings)
{
   myTable.Rows.Add(ref oMissing)
   // do somethign to the row here. add strings etc. 
   myTable.Rows.[rowCount].Cells[1].Range.Text = "Content of column 1";
   myTable.Rows[rowCount].Cells[2].Range.Text = "Content of column 2";
   myTable.Rows[rowCount].Cells[3].Range.Text = "Content of column 3";
   //etc
   rowCount++;
}

I have not tested this code but should work...