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

模板 – 使用Open Xml替换Word文档中的文本

发布时间:2020-12-16 07:42:47 所属栏目:百科 来源:网络整理
导读:我已经从单词模板创建了一个docx文件,现在我正在访问复制的docx文件,并希望用某些其他数据替换某些文本. 我无法获得关于如何从主要部分访问文本的提示? 任何帮助将是可观的. 以下是我的代码. private void CreateSampleWordDocument() { //string sourceFil
我已经从单词模板创建了一个docx文件,现在我正在访问复制的docx文件,并希望用某些其他数据替换某些文本.

我无法获得关于如何从主要部分访问文本的提示?

任何帮助将是可观的.

以下是我的代码.

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
        {
        }
    }

现在如何找到某些文字并替换相同?
我无法通过链接,所以一些代码提示将是可观的.

只是给你想法如何做,请尝试:
using ( WordprocessingDocument doc =
                    WordprocessingDocument.Open(@"yourpathtestdocument.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");
                            }
                        }
                    }
                }
            }
        }

请注意,文本区分大小写.替换后,文本格式不会更改.希望这可以帮助你.

(编辑:李大同)

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

    推荐文章
      热点阅读