delphi 如何替换Word文档中的文本  
官方Delphi 学习QQ群: 682628230(三千人)
频道

delphi 如何替换Word文档中的文本


use ActiveX, ComObj;

const 
  wdFindContinue = 1;
  wdReplaceOne = 1;
  wdReplaceAll = 2;

var 
  WordApp: Variant;

begin
  // create OLE object for MS Word application:
  WordApp := CreateOLEObject('Word.Application');
  // load a document from your file
  WordApp.Documents.Open(yourDocFileName);
  WordApp.Selection.Find.ClearFormatting;
  WordApp.Selection.Find.Text := yourStringForSearch;
  WordApp.Selection.Find.Replacement.Text := yourNewStringForReplace;
  WordApp.Selection.Find.Forward := True;
  WordApp.Selection.Find.MatchAllWordForms := False;
  WordApp.Selection.Find.MatchCase := Flase;
  WordApp.Selection.Find.MatchWildcards := False;
  WordApp.Selection.Find.MatchSoundsLike := False;
  WordApp.Selection.Find.MatchWholeWord := False;
  WordApp.Selection.Find.MatchFuzzy := False;
  WordApp.Selection.Find.Wrap := wdFindContinue; 
  WordApp.Selection.Find.Format := False;
  
  WordApp.Selection.Find.Execute(Replace := wdReplaceAll)
end;

//要替换首次出现的文字,请使用
WordApp.Selection.Find.Execute(Replace := wdReplaceOne);
替换
WordApp.Selection.Find.Execute(Replace := wdReplaceAll)

//要检查是否找到了文本,请使用Found方法:
if WordApp.Selection.Find.Found then
  {do something}
Save the modified document with:

WordApp.ActiveDocument.SaveAs(yourDocFileName);

//最后,使用以下命令关闭MS Word实例:
WordApp.ActiveDocument.Close;
WordApp.Quit;
WordApp := Unassigned;
注意:
如果要更改字体而不是文本,请使用WordApp.Selection.Find.Replacement的Font 属性而不是 Text。

推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.036579132080078 seconds