Here is a more detailed example where you add 5 rows to a existing table.
This assumes that the table is the first one in the document. If not you have to find your table.
The code gets the last row of the table and copies it. After that you just need to fill in your data in the cells.
Table myTable = doc.Body.Descendants<Table>().First();
TableRow theRow = myTable.Elements<TableRow>().Last();
for (int i = 0; i < 5; i++)
{
TableRow rowCopy = (TableRow)theRow.CloneNode(true);
var runProperties = GetRunPropertyFromTableCell(rowCopy, 0);
var run = new Run(new Text(i.ToString() + " 1"));
run.PrependChild<RunProperties>(runProperties);
rowCopy.Descendants<TableCell>().ElementAt(0).RemoveAllChildren<Paragraph>();//removes that text of the copied cell
rowCopy.Descendants<TableCell>().ElementAt(0).Append(new Paragraph(run));
//I only get the the run properties from the first cell in this example, the rest of the cells get the document default style.
rowCopy.Descendants<TableCell>().ElementAt(1).RemoveAllChildren<Paragraph>();
rowCopy.Descendants<TableCell>().ElementAt(1).Append(new Paragraph(new Run(new Text(i.ToString() + " 2"))));
rowCopy.Descendants<TableCell>().ElementAt(2).RemoveAllChildren<Paragraph>();
rowCopy.Descendants<TableCell>().ElementAt(2).Append(new Paragraph(new Run(new Text(i.ToString() + " 3"))));
myTable.AppendChild(rowCopy);
}
myTable.RemoveChild(theRow); //you may want to remove this line. I have it because in my code i always have a empty row last in the table that i copy.
The GetRunPropertiesFromTableCell is my quick hack attempt of using the same format for the text as the existing rows already have.
private static RunProperties GetRunPropertyFromTableCell(TableRow rowCopy, int cellIndex)
{
var runProperties = new RunProperties();
var fontname = "Calibri";
var fontSize = "18";
try
{
fontname =
rowCopy.Descendants<TableCell>()
.ElementAt(cellIndex)
.GetFirstChild<Paragraph>()
.GetFirstChild<ParagraphProperties>()
.GetFirstChild<ParagraphMarkRunProperties>()
.GetFirstChild<RunFonts>()
.Ascii;
}
catch
{
//swallow
}
try
{
fontSize =
rowCopy.Descendants<TableCell>()
.ElementAt(cellIndex)
.GetFirstChild<Paragraph>()
.GetFirstChild<ParagraphProperties>()
.GetFirstChild<ParagraphMarkRunProperties>()
.GetFirstChild<FontSize>()
.Val;
}
catch
{
//swallow
}
runProperties.AppendChild(new RunFonts() { Ascii = fontname });
runProperties.AppendChild(new FontSize() { Val = fontSize });
return runProperties;
}