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