python操作word文档替换文字_pythonwin32com自动化Word如何替换文本框中的文本?

我试图用Python自动化word来替换word文档中的文本。(如果重要的话,我使用word2003和python2.4)

下面的replace方法的第一部分适用于除文本框中的文本之外的所有内容。文本就是没有被选中。我注意到当我手动进入Word并按ctrl-A时,除了文本框之外,所有的文本都被选中了。在

以下是我目前为止的代码:class Word:

def __init__(self,visible=0,screenupdating=0):

pythoncom.CoInitialize()

self.app=gencache.EnsureDispatch(WORD)

self.app.Visible = visible

self.app.DisplayAlerts = 0

self.app.ScreenUpdating = screenupdating

print 'Starting word'

def open(self,doc):

self.opendoc=os.path.basename(doc)

self.app.Documents.Open(FileName=doc)

def replace(self,source,target):

if target=='':target=' '

alltext=self.app.Documents(self.opendoc).Range(Start=0,End=self.app.Documents(self.opendoc).Characters.Count) #select all

alltext.Find.Text = source

alltext.Find.Replacement.Text = target

alltext.Find.Execute(Replace=1,Forward=True)

#Special handling to do replace in text boxes

#http://word.tips.net/Pages/T003879_Updating_a_Field_in_a_Text_Box.html

for shp in self.app.Documents(self.opendoc).Shapes:

if shp.TextFrame.HasText:

shp.TextFrame.TextRange.Find.Text = source

shp.TextFrame.TextRange.Find.Replacement.Text = target

shp.TextFrame.TextRange.Find.Execute(Replace=1,Forward=True)

#My Usage

word=Word(visible=1,screenupdating=1)

word.open(r'C:\Invoice Automation\testTB.doc')

word.replace('[PGN]','1')

用于shp输入自我.app.. 第二节是我尝试点击文本框。它似乎找到了文本框,但它没有替换任何内容。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值