Written on 2009年6月9日 @ 16:07 | by spirit | Tags: C#  office   | 浏览:

    C#操作WORD替换字符串的思路是在文档中搜索和替换字符串,先在word文档中标记字符串,然后再搜索标记字符串并用新的字符串替换标记字符串。

说明:其中oDoc是一个word文档的Document对象,需要先打开一个word文档才能操作。




        ///<summary>
        /// 在word 中查找一个字符串直接替换所需要的文本
        /// </summary>
        /// <param name="strOldText">原文本</param>
        /// <param name="strNewText">新文本</param>
        /// <returns></returns>
        public bool Replace(string strOldText,string strNewText)
        {
            this.oDoc.Content.Find.Text = strOldText ;
            object FindText,  ReplaceWith, Replace ;// 
            object MissingValue = Type.Missing; 
            FindText = strOldText ;//要查找的文本
            ReplaceWith = strNewText ;//替换文本
               Replace = Word.WdReplace.wdReplaceAll ;/**//*wdReplaceAll - 替换找到的所有项。
                                                      * wdReplaceNone - 不替换找到的任何项。
                                                    * wdReplaceOne - 替换找到的第一项。
                                                    * */
            this.oDoc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
            if (this.oDoc.Content.Find.Execute(
                ref FindText,ref MissingValue,
                ref MissingValue,ref MissingValue,
                ref MissingValue,ref MissingValue,
                ref MissingValue,ref MissingValue,ref MissingValue,
                ref ReplaceWith,ref Replace,
                ref MissingValue,ref MissingValue,
                ref MissingValue,ref MissingValue))
            {
                return true ;
            }
            return false ;
            
        }


若转载请注明出处: Spirit's Home
本文地址: http://www.7788sky.cn/post/csharp_word_find_string.html
  1. 0 Response to “C#操作WORD替换字符串”

Post a Comment

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。