RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
浅析C#Word文档替换操作

浅析C#Word文档替换操作的操作时在文档中搜索和替换字符串,先在word文档中标记字符串,然后再搜索标记字符串并用新的字符串替换标记字符串.主要是先选择整个文档,然后使用Find的Execute方法查找指定字符串并替换为相应字符串.

成都创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:网站制作、成都做网站、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的辽宁网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

以下实现浅析C#Word文档替换操作的方式:

使用文档(Document )对象的 Content 属性选择整个文档。

 
 
 
  1.  ///﹤summary﹥  
  2. /// 浅析C#Word文档替换操作,在word 中查找一个字符串直接替换所需要的文本  
  3. /// ﹤/summary﹥  
  4. /// ﹤param name="strOldText"﹥原文本﹤/param﹥  
  5. /// ﹤param name="strNewText"﹥新文本﹤/param﹥  
  6. /// ﹤returns﹥﹤/returns﹥  
  7. public bool Replace(string strOldText,string strNewText)  
  8. {  
  9. this.oDoc.Content.Find.Text = strOldText ;  
  10. object FindText,  ReplaceWith, Replace ;//   
  11. object MissingValue = Type.Missing;   
  12. FindText = strOldText ;//要查找的文本  
  13. ReplaceWith = strNewText ;//替换文本  
  14.    Replace = Word.WdReplace.wdReplaceAll ;  
  15. /**//*wdReplaceAll - 替换找到的所有项。  
  16.   * wdReplaceNone - 不替换找到的任何项。  
  17. * wdReplaceOne - 替换找到的第一项。  
  18. * */ 
  19. this.oDoc.Content.Find.ClearFormatting();  
  20. //移除Find的搜索文本和段落格式设置  
  21. if (this.oDoc.Content.Find.Execute(  
  22. ref FindText,ref MissingValue,  
  23. ref MissingValue,ref MissingValue,  
  24. ref MissingValue,ref MissingValue,  
  25. ref MissingValue,ref MissingValue,ref MissingValue,  
  26. ref ReplaceWith,ref Replace,  
  27. ref MissingValue,ref MissingValue,  
  28. ref MissingValue,ref MissingValue))  
  29. {  
  30. return true ;  
  31. }  
  32. return false ;  
  33.  
  34. }  

说明:其中oDoc是一个word文档的Document对象.

此外还可以运用Word Application 对象Selection的Find实现浅析C#Word文档替换操作.

 
 
 
  1. public bool SearchReplace(string strOldText,string strNewText)  
  2. {   
  3. object replaceAll = Word.WdReplace.wdReplaceAll;   
  4. object missing = Type.Missing;   
  5.  
  6. //首先清除任何现有的格式设置选项,然后设置搜索字符串 strOldText。  
  7. this.oWordApplic.Selection.Find.ClearFormatting();   
  8. oWordApplic.Selection.Find.Text = strOldText;   
  9.  
  10. oWordApplic.Selection.Find.Replacement.ClearFormatting();   
  11. oWordApplic.Selection.Find.Replacement.Text = strNewText;   
  12.  
  13. if (oWordApplic.Selection.Find.Execute(  
  14. ref missing, ref missing,   
  15. ref missing, ref missing, ref missing,   
  16. ref missing, ref missing,   
  17. ref missing, ref missing, ref missing,  
  18. ref replaceAll, ref missing,   
  19. ref missing, ref missing, ref missing))  
  20. {  
  21. return true ;  
  22. }  
  23. return false ;  
  24. }  

注:oWordApplic是一个Word Application 对象

当然也可以使用word文档的书签BookMark.使用 Bookmark 的 Range 属性可将文本插入占位符书签,以便能够在以后检索文本,或替换已包含文本的书签中的文本。

浅析C#Word文档替换操作的具体内容就向你介绍到这里,希望对你了解和学习浅析C#Word文档替换操作有所帮助。


网页标题:浅析C#Word文档替换操作
网站链接:http://www.jxjierui.cn/article/cosgecd.html