簡體   English   中英

使用win32com.client api打開MS Word 2016和訪問formFileds時如何解決AttributeError?

[英]How to resolve AttributeError when using win32com.client api for opening MS word 2016 and access formFileds?

我正在努力使用python自動生成報告。 在Word文檔中,我需要更新“表單字段”以完成報告的生成。 在使用win32.com.client.gencache.EnsureDispatch api時,我無法從Word文檔中獲取formFields。

以下是編寫的腳本:

我收到以下錯誤:

    raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
AttributeError: '<win32com.gen_py.Microsoft Word 16.0 Object Library.FormFields instance at 0x2217380698888>' object has no attribute '__getitem__'

我試圖搜索有關如何使Word文檔中存在FormField的幫助,但找不到關於我遇到的錯誤的任何適當文檔。

word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible='False'
file = os.path.abspath(path)
d = word.Documents.Open(file)
d.FormFields[0].Result = reviewer

d.FormFields [0] .Result應該是有效的屬性。

在打印d ,必須知道該對象完全不包含任何FormField。

['CLSID', '__doc__', '__getattr__', '__init__', '__module__', '__repr__', '__setattr__', '_dispobj_', 'coclass_interfaces', 'coclass_sources', 'default_interface', 'default_source']

您的變量d不包含Python對象。 它包含帶有VBA接口的COM對象周圍的薄Python包裝器。

打印Python對象的dir將向您顯示其Python屬性。 但是FormFields是COM對象的VBA屬性。 打印dir(d)將不會顯示COM對象的VBA屬性。

但是,如果您的文檔中有表單,則可以這樣查看:

>>> list (d.FormFields)

再次查看您的錯誤消息。 它說

AttributeError: '<win32com.gen_py.Microsoft Word 16.0 Object Library.FormFields instance at 0x2217380698888>' object has no attribute '__getitem__'

該錯誤消息確認VBA對象FormFields是有效屬性,並且確實存在,因為該消息為其Python包裝器提供了內存位置。

您的問題在別處。 我懷疑FormFields不包含您期望的內容。 其中必須包含某些內容,因為否則會得到IndexError ,但是可以按以下方式檢查它:

>>> d.FormFields.Count

如果您想知道COM對象的屬性是什么,請查閱VBA文檔。

附帶說明一下,在這個初學者的階段,您真的不應該花時間在學習Python 2上。對Python 2的支持將於今年年底停止。 我們中有些人別無選擇,只能繼續使用Python 2進行工作,但是如果您有選擇,請立即切換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM