加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:08:37 所属栏目:百科 来源:网络整理
导读:我需要使用现有的表(例如,3列)打开现有的Word文档(.docx),并向该表添加一个新行.有什么办法吗我正在使用Open XML 我正在创建这样的表(第一次): Table tbl = new Table();// Set the style and width for the table.TableProperties tableProp = new TablePr
我需要使用现有的表(例如,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"))))));
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读