ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-11-06 16:06:38  阅读:1385  来源: 互联网

标签:win32com python vba ms-word


我正在尝试使用Python自动执行单词替换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')

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

这两种方法都可以在我的测试代码中使用.

标签:win32com,python,vba,ms-word
来源: https://codeday.me/bug/20191106/1999470.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有