簡體   English   中英

Python win32com - 自動化Word - 如何替換文本框中的文本?

[英]Python win32com - Automating Word - How to replace text in a text box?

我正在嘗試使用Python自動化word替換word文檔中的文本。 (如果重要的話,我會在2003年的文字和Python 2.4)

我的替換方法的第一部分適用於除文本框中的文本之外的所有內容。 文本沒有被選中。 我注意到當我手動進入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')

self.app ..部分中的for shp是我嘗試點擊文本框。 它似乎找到了文本框,但它並沒有取代任何東西。

當我向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)

這兩種方法都適用於我的測試代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM