替换控件内容中的文字

时间:2017-06-22 13:56:45

标签: c# .net ms-word openxml

我有一个单词模板,我需要在一些精确的位置更改一些文本。

我已经完成了一个标题,但我只使用了InnerXML,我可以尝试不使用这个函数,它可能会更好。

我的代码:

using (WordprocessingDocument myDoc = WordprocessingDocument.Open(destinationFile, true))
{
    var mainDocumentPart = myDoc.MainDocumentPart;

    //Body
    var body = mainDocumentPart.Document.Body;
    List<SdtElement> SdtBlocks = myDoc.MainDocumentPart.Document.Descendants<SdtElement>().ToList();

    //var text = SdtBlocks[0].Descendants<Text>().First().Text;
    //SdtBlocks[0].Descendants<Text>().First().Text.Replace(SdtBlocks[0].InnerText, cv.Resume);

    foreach (var element in SdtBlocks)
    {
        if (element.InnerText.Contains("Resume"))
        {
            element.Descendants<Text>().First().Text = cv.Resume;
            System.Diagnostics.Debug.WriteLine(element.Descendants<Text>().First().Text);
        }
        //foreach(var text in element.Descendants<Text>())
        //{
        //}
    }

cv是我的数据对象。

实际上,这样做并不会改变包含&#34; Resume&#34;在我的最后一句话。 另外,我会在这个单词上添加一些列表,但我不知道该怎么做。我试图在互联网和openXML相关网站上找到一些信息(包括Eric White的一个),但我找不到解决方案。

有任何想法并解决这个问题以及第二部分吗?

编辑 :所以我终于修复了第一部分,感谢@petedelis:

var text = SdtBlocks[0].Descendants<Text>().First().Text;
Paragraph newParagraph = new Paragraph();
Run newRun = new Run();
Text newText = new Text(cv.Resume);
newRun.Append(newText);
newParagraph.Append(newRun);
SdtBlocks[0].Parent.InsertBefore(newParagraph, SdtBlocks[0]);
SdtBlocks[0].Remove();

现在我在桌子上:我的表格如下:Image of the template

我需要为每个任务复制第二行。其实我有这个:

foreach (Mission mission in listeMission)
                {
                    SdtRow newRow = new SdtRow();
                    SdtContentRow newContent = new SdtContentRow();
                    newParagraph = new Paragraph();
                    newRun = new Run();
                    Text cell = new Text(mission.Titre);
                    newRun.Append(cell);
                    newParagraph.Append(newRun);
                    newContent.Append(newParagraph);
                    newRow.Append(newContent);
                    rowTemplate.RemoveAllChildren();
                    rowTemplate.Append(newContent);
                    rowTemplate.Parent.InsertBeforeSelf(newRow);
}

但结果不是我想要的。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

你说你找到了文档中的第一个表,然后是这个表的第二行,带有这个代码:

// Find the first table in the document. 
Table table = myDoc.MainDocumentPart.Document.Body.Elements<Table>().Skip(‌​1).First(); 
// Find the second row in the table. 
SdtRow rowTemplate = table.Elements<SdtRow>().First();

我认为你实际上是在文档中找到第二个表,然后是这个表的第一行。

也许尝试以下方法?

// Find the first table in the document. 
Table table = myDoc.MainDocumentPart.Document.Body.Elements<Table>().First(); 
// Find the second row in the table. 
SdtRow rowTemplate = table.Elements<SdtRow>().Skip(1).First();
相关问题