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

核能气质少年 提交于 2019-11-26 17:24:35

问题


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?


回答1:


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...




回答2:


I found it, it should be:

Object oMissing = System.Reflection.Missing.Value;
oWordDoc.Tables[2].Rows.Add(ref oMissing); 


来源:https://stackoverflow.com/questions/20662818/add-a-row-to-an-ms-word-table-using-office-interop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!