使用打开Xml替换Word文档中的文本 [英] Replace Text in Word document using Open Xml

查看:207
本文介绍了使用打开Xml替换Word文档中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从字模板创建了一个docx文件,现在我正在访问复制的docx文件,并想用某些其他数据替换某些文本。

I have created a docx file from a word template, now I am accessing the copied docx file and want to replace certain text with some other data.

无法获得如何访问文本主体部分的文本的提示?

I am unable to get the hint as to how to access the text from the doument main part?

任何帮助都是可以接受的。

Any help would be appreciable.

下面是我的代码。

private void CreateSampleWordDocument()
    {
        //string sourceFile = Path.Combine("D:\\GeneralLetter.dot");
        //string destinationFile = Path.Combine("D:\\New.doc");
        string sourceFile = Path.Combine("D:\\GeneralWelcomeLetter.docx");
        string destinationFile = Path.Combine("D:\\New.docx");
        try
        {
            // Create a copy of the template file and open the copy
            File.Copy(sourceFile, destinationFile, true);
            using (WordprocessingDocument document = WordprocessingDocument.Open(destinationFile, true))
            {
                // Change the document type to Document
                document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
                //Get the Main Part of the document
                MainDocumentPart mainPart = document.MainDocumentPart;
                mainPart.Document.Save();
            }
        }
        catch
        {
        }
    }

现在如何找到某些文本并替换相同的文本?
我无法通过链接获得,所以一些代码提示会是明显的。

Now how to find certain text and replace the same? I am unable to get via Link, so some code hint would be appreciable.

推荐答案

请尝试:

  using ( WordprocessingDocument doc =
                    WordprocessingDocument.Open(@"yourpath\testdocument.docx", true))
            {
                var body = doc.MainDocumentPart.Document.Body;
                var paras = body.Elements<Paragraph>();

                foreach (var para in paras)
                {
                    foreach (var run in para.Elements<Run>())
                    {
                        foreach (var text in run.Elements<Text>())
                        {
                            if (text.Text.Contains("text-to-replace"))
                            {
                                text.Text = text.Text.Replace("text-to-replace", "replaced-text");
                            }
                        }
                    }
                }
            }
        }

请注意,文本区分大小写。替换后文本格式不会更改。希望这有助于你。

Please note the text is case sensitive. The text formatting won't be changed after the replace. Hope this helps you.

这篇关于使用打开Xml替换Word文档中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆