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

发布于 2024-09-05 10:44:35 字数 1599 浏览 2 评论 0原文

我正在尝试使用 Python 自动化 Word 来替换 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 .. 部分是我尝试点击文本框。它似乎找到了文本框,但它没有替换任何内容。

I'm trying to automate word to replace text in a word document using Python. (I'm on word 2003 if that matters and Python 2.4)

The first part of my replace method below works on everything except text in text boxes. The text just doesn't get selected. I notice when I go into Word manually and hit ctrl-A all of the text gets selected except for the text box.

Here's my code so far:

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

The for shp in self.app .. section is my attempt to hit the text boxes. It seems to find the text box, but it doesn't replace anything.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦晓ヶ微光ヅ倾城 2024-09-12 10:44:37

当我将文本框添加到 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)

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

When I add text boxes to a word document, they are added inside a drawing canvas. Therefore the top level shape is the canvas, and the text boxes are contained within the canvas. You should use the CanvasItems method to access the objects in the canvas, ie the text boxes

The following example works for me. I created a word document with a single text box.

import win32com.client

word = win32com.client.Dispatch("Word.Application")
canvas = word.ActiveDocument.Shapes[0]
for item in canvas.CanvasItems:
    print item.TextFrame.TextRange.Text

Update: answering OP's comment.

I think the problem with your code is that each line of code with Find creates a new Find object. You have to create and bind a Find object to a name, then modify its attributes and execute it. So in your code you should have:

find = shp.TextFrame.TextRange.Find
find.Text = source
find.Replacement.Text = target
find.Execute(Replace=1, Forward=True)

Or a single line:

shp.TextFrame.TextRange.Find.Execute(FindText=source, ReplaceWith=target, Replace=1, Forward=True)

Both of these methods work in my test code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文