c# – 将一行添加到Word文档中的现有表(打开的XML)

前端之家收集整理的这篇文章主要介绍了c# – 将一行添加到Word文档中的现有表(打开的XML)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要使用现有的表(例如,3列)打开现有的Word文档(.docx),并向该表添加一个新行.有什么办法吗我正在使用Open XML

我正在创建这样的表(第一次):

Table tbl = new Table();

// Set the style and width for the table.
TableProperties tableProp = new TableProperties();
TableStyle tableStyle = new TableStyle() { Val = "TableGrid" };

// Make the table width 100% of the page width.
TableWidth tableWidth = new TableWidth() { Width = "5000",Type = TableWidthUnitValues.Pct };

// Apply
tableProp.Append(tableStyle,tableWidth);
tbl.AppendChild(tableProp);

// Add 3 columns to the table.
TableGrid tg = new TableGrid(new GridColumn(),new GridColumn(),new GridColumn());
tbl.AppendChild(tg);

// Create 1 row to the table.
TableRow tr1 = new TableRow();

// Add a cell to each column in the row.
TableCell tc1 = new TableCell(new Paragraph(new Run(new Text("1"))));
TableCell tc2 = new TableCell(new Paragraph(new Run(new Text("2"))));
TableCell tc3 = new TableCell(new Paragraph(new Run(new Text("3"))));
tr1.Append(tc1,tc2,tc3);

// Add row to the table.
tbl.AppendChild(tr1);
return tbl;

解决方法

干得好,
Body bod = doc.MainDocumentPart.Document.Body;
foreach (Table t in bod.Descendants<Table>())
{
    t.Append(new TableRow(new TableCell(new Paragraph(new Run(new Text("test"))))));
}

使用LINQ获取正确的表.

编辑:

假设你想得到有4列的表.

Body bod = doc.MainDocumentPart.Document.Body;
foreach (Table t in bod.Descendants<Table>().Where(tbl => tbl.GetFirstChild<TableRow>().Descendants<TableCell>().Count() == 4))
{
    t.Append(new TableRow(new TableCell(new Paragraph(new Run(new Text("test"))))));
}

假设你想得到包含“mytable”一词的表格.

Body bod = doc.MainDocumentPart.Document.Body;
foreach (Table t in bod.Descendants<Table>().Where(tbl => tbl.InnerText.Contains("myTable")))
{
    t.Append(new TableRow(new TableCell(new Paragraph(new Run(new Text("test"))))));
}

猜你在找的C#相关文章