使用Office.Interop将一行添加到MS Word表

时间:2013-12-18 16:01:44

标签: c# ms-word office-interop

我有一个带有表格的单词模板,我从一个字符串列表填充,我使用制表符分割。

我不知道会有多少行文字,因为它会有所不同。

所以我在迭代循环之前以编程方式添加一行,如下所示:

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

不幸的是,它是在行之前而不是在当前行之后添加行。

如何将代码更改为在当前行之后添加空行?

2 个答案:

答案 0 :(得分:5)

将参数值保留为Row.Add函数

的缺失值
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++;
}

我还没有测试过这段代码,但应该可以运行......

答案 1 :(得分:3)

我找到了,它应该是:

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