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

标签 python vba ms-word win32com

我正在尝试使用 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')

for shp in self.app .. 部分是我尝试点击文本框。它似乎找到了文本框,但它没有替换任何东西。

最佳答案

当我将文本框添加到 Word 文档时,它们会添加到绘图 Canvas 中。因此,顶级形状是 Canvas ,文本框包含在 Canvas 中。您应该使用 CanvasItems 方法来访问 Canvas 中的对象,即文本框

以下示例对我有用。我创建了一个带有单个文本框的 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 对象并将其绑定(bind)到一个名称,然后修改其属性并执行它。所以在你的代码中你应该有:

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)

这两种方法都适用于我的测试代码。

关于Python win32com - 自动化 Word - 如何替换文本框中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3022898/

相关文章:

excel - Range对象InputBox问题(空值)

c# - 在 Windows 服务中打开 Microsoft Word 文档似乎挂起

css - 将 HTML 文档与不同的字符集结合起来

python - django 2 mysql 数据库后端不接受 0 作为 AutoField 错误的值

Excel VBA结束选择没有选择案例

ms-access - MS Access 表单字段中的拼写检查代码 - 接受更改时抛出错误

c# - VSTO MS Word 2003 加载项导致错误 "Word experienced a serious error the last time the add-in ' XYZ' 已打开”

python - 在 Mac OS X Yosemite 上安装 PyGMO - 缺少 boost-python3?

python - Shell 脚本无法识别别名

python - 如何从字符串中提取命令 - python