这是一个更详细的示例,您将 5 行添加到现有表中。
这假定表格是文档中的第一个表格。如果没有,你必须找到你的桌子。
代码获取表的最后一行并将其复制。之后,您只需在单元格中填写您的数据。
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.
GetRunPropertiesFromTableCell 是我对文本使用与现有行已有的相同格式的快速破解尝试。
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;
}