4

Python を使用して、Word 文書内のテキストを置換するために Word を自動化しようとしています。(それが重要な場合はWord 2003とPython 2.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')

for shp in self.app .. セクションは、テキスト ボックスをヒットする私の試みです。テキストボックスが見つかったようですが、何も置き換えられません。

4

1 に答える 1

5

Word 文書にテキスト ボックスを追加すると、描画キャンバス内に追加されます。したがって、最上位の形状はキャンバスであり、テキスト ボックスはキャンバス内に含まれています。メソッドを使用CanvasItemsして、キャンバス内のオブジェクト、つまりテキスト ボックスにアクセスする必要があります。

次の例は私にとってはうまくいきます。テキスト ボックスが 1 つの 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)

これらの方法は両方とも、私のテスト コードで機能します。

于 2010-06-11T14:24:32.993 に答える