获取特定文本字符串所在表格的格式,并创建具有相同格式

时间:2015-10-01 18:07:00

标签: c# openxml document

在C#中使用OpenXML,我们需要:

  1. 在Word文档中查找特定的文本字符串(此文本将始终存在于表格单元格中
  2. 获取文本和文本所在表格的格式。
  3. 创建一个具有相同文本和表格格式的新表格,同时从嵌套列表中提取单元格的文本值
  4. 这是我目前拥有的代码以及我不知道如何做的地方:

    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileWordFile, true))
    {
        MainDocumentPart mainPart = wordDoc.MainDocumentPart;
        Body body = mainPart.Document.Body;
        IEnumerable paragraphs = body.Elements<Paragraph>();
        Paragraph targetParagraph = null;
        //Comment 1: Loop through paragraphs and search for a specific string of text in word document
        foreach (Paragraph paragraph in paragraphs) {
            if(paragraph.Elements<Run>().Any()) {
                Run run = paragraph.Elements<Run>().First();
                if(run.Elements<Text>().Any()) {
                    Text text = run.Elements<Text>().First();
                    if (text.Text.Equals("MY SEARCH STRING")) {
                        targetParagraph = paragraph;
                        // Comment 2: How can I get the formatting of the table that contains this text??
    
                    }
                }
            }
        }
    
        //Comment 3: Create table with same formatting as where the text was found
        Table table1 = new Table();
        TableProperties tableProperties1 = new TableProperties();
        //Comment 4: How can I set these properties to be the same as the one found at "Comment 2"??
    
    
        wordDoc.Close();
        wordDoc.Dispose();
    }
    

1 个答案:

答案 0 :(得分:0)

如果要查找表格单元格内的文本元素,可以使用LINQ查询快速到达,而无需使用嵌套循环堆。

// Find the first text element matching the search string 
// where the text is inside a table cell.
var textElement = body.Descendants<Text>()
                      .FirstOrDefault(t => t.Text == searchString && 
                                           t.Ancestors<TableCell>().Any());

完成匹配后,复制包含表及其所有格式和内容的最简单方法就是克隆它。

if (textElement != null)
{
    // get the table containing the matched text element and clone it
    Table table = textElement.Ancestors<Table>().First();
    Table tableCopy = (Table)table.CloneNode(deep: true);

    // do stuff with copied table (see below)
}

之后,您可以将内容添加到复制表的相应单元格中。通过“从嵌套列表中提取单元格的文本值”(什么列表?嵌套在哪里?),你的意思并不完全清楚,所以我只是展示一个人为的例子。 (此代码将替换上面代码中的“do stuff”注释。)

    // find the table cell containing the search string in the copied table
    var targetCell = tableCopy.Descendants<Text>()
                              .First(t => t.InnerText == searchString)
                              .Ancestors<TableCell>()
                              .First();

    // get the properties from the first paragraph in the target cell (so we can copy them)
    var paraProps = targetCell.Descendants<ParagraphProperties>().First();

    // now add new stuff to the target cell
    List<string> stuffToAdd = new List<string> { "foo", "bar", "baz", "quux" };
    foreach (string item in stuffToAdd)
    {
        // for each item, clone the paragraph properties, then add a new paragraph
        var propsCopy = (ParagraphProperties)paraProps.CloneNode(deep: true);
        targetCell.AppendChild(new Paragraph(propsCopy, new Run(new Text(item))));
    }

最后,您需要将复制的表格添加到文档中,否则您将看不到它。你没有在你的问题中说出你希望它出现在哪里,所以我只是把它放在文档的末尾。您可以使用InsertAfterInsertAtInsertBefore等方法将表格相对于其他元素插入。

    body.AppendChild(tableCopy);

希望这有帮助。

相关问题