Python win32com - 自动化Word - 如何替换文本框中的文本?

问题描述:

我正在尝试使用Python自动化词语以替换word文档中的文本。 (我在Word 2003中,如果这很重要,Python 2.4)Python win32com - 自动化Word - 如何替换文本框中的文本?

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

这里是到目前为止我的代码:

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') 

的在self.app SHP ..部分是我试图打的文本框中。它似乎找到了文本框,但它不能代替任何东西。

+0

我已根据您对我的原始答案的评论更新了我的答案。 – 2010-06-13 12:26:23

当我将文本框添加到word文档时,它们被添加到绘图画布内。因此,顶层形状是画布,文本框包含在画布内。您应该使用CanvasItems方法访问画布中的对象,即文本框

以下示例适用于我。我用一个文本框创建了一个word文档。

import win32com.client 

word = win32com.client.Dispatch("Word.Application") 
canvas = word.ActiveDocument.Shapes[0] 
for item in canvas.CanvasItems: 
    print item.TextFrame.TextRange.Text 

更新:在回答OP的评论。

我认为你的代码存在的问题是每行代码与Find创建一个新的Find对象。您必须创建并将一个Find对象绑定到名称,然后修改其属性并执行它。所以,在你的代码,你应该有:

find = shp.TextFrame.TextRange.Find 
find.Text = source 
find.Replacement.Text = target 
find.Execute(Replace=1, Forward=True) 

或者单行:

shp.TextFrame.TextRange.Find.Execute(FindText=source, ReplaceWith=target, Replace=1, Forward=True) 

在我的测试代码,这两种方法的工作。

+0

我可以访问文本框(运行print shp.TextFrame.TextRange打印文本。)它只是查找和替换,似乎没有工作。你的方法找到并替换工作吗? – Greg 2010-06-11 14:27:53

+0

酷豆,谢谢! – Greg 2010-06-14 02:24:01