簡體   English   中英

如何使用win32com.client api訪問MS word的腳注

[英]How to access footnotes of MS word by using win32com.client api

我正在嘗試使用 win32com.client api 訪問 MS word 文件的腳注。

我已經用谷歌搜索了,但我沒有找到合適的方法。 我將 python-docx 用於上述目的,但我發現當前版本的 python-docx 無法訪問 MS Word 文件的腳注。

因此,我目前正在考慮使用 win32com.client api。 我可以在 MS Word 文檔中找到某些單詞並使用以下代碼替換它們。

import win32com.client as win32
word = win32.gencache.EnsureDispatch("Word.application")
word.Visible = True

# ================== part 1 ===============================

word.Documents.Open('C:\\Users\\wanak\\Desktop\\Temp\\Test.docx')
word.Selection.Find.Text = "Kim"
word.Selection.Find.Replacement.Text = "Lee"
word.Selection.Find.Execute(Replace=2, Forward=True)

# ================== part 2 ===============================

footnotes = word.ActiveDocument.StoryRanges(wdFootnotesStory)
footnotes.Selection.Find.Text = "Kim"
footnotes.Selection.Find.Replacement.Text = "Lee"
footnotes.Selection.Find.Execute(Replace=2, Forward=True)

上述代碼中的第 1 部分可以正常工作,但無法訪問腳注。

第 2 部分也無法找到和替換腳注中的單詞。 僅出現錯誤消息“NameError: name 'wdFootnotesStory' is not defined”。

我在 stackoverflow 中找到了一個類似的問題和答案,但答案中的代碼不起作用,並且出現相同的錯誤消息。

使用Python在word中查找和替換腳注

如果有人讓我知道如何訪問 MS Word 文檔中的腳注,我將不勝感激。

我找到了解決方案。 第 2 部分應更改如下

footnotes = word.ActiveDocument.StoryRanges(win32.constants.wdFootnotesStory)
for i in range(0, 4) : # 4 is number of words to be changed
    footnotes.Find.Execute(FindText="kim", Forward=True)
    footnotes.Text = footnotes.Text.replace("kim", "lee")
    footnotes = word.ActiveDocument.StoryRanges(win32.constants.wdFootnotesStory)

暫無
暫無

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

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