如何进行Word document内容替换

本文转载:http://www.delphidabbler.com/tips/136 

How to replace text in a Word document

Here's how to use OLE automation for MS Word and replace some text string in any document.

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 := False;
  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;


 

To replace the first occurence of your text only use  (只替换第一次出现的文本,这样使用:)

To replace the first occurence of your text only use 


 Instead of (全部替换,这样使用:)

WordApp.Selection.Find.Execute(Replace := wdReplaceAll)


To check if text was found then use the Found method: (检查在word中是否能找到文本,使用Found方法:)

if WordApp.Selection.Find.Found then
  {do something}


Save the modified document with: (保存修改后的文档的方法:)

WordApp.ActiveDocument.SaveAs(yourDocFileName);


Finally, close the MS Word instance with: (关闭文档实例这样使用:)

WordApp.ActiveDocument.Close;
WordApp.Quit;
WordApp := Unassigned;

 

注意:若想更换替换文本的字体,使用WordApp.Selection.Find.Replacement 的Font属性。

Note 
If you want to change a font instead text, use the Font property of WordApp.Selection.Find.Replacement instead of Text. 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值