2010-06-11 116 views
3

我正在嘗試使用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

回答

4

當我將文本框添加到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