繁体   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