简体   繁体   English

如何使用win32com.client api访问MS word的脚注

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

I am trying to access footnotes of MS word file by using win32com.client api.我正在尝试使用 win32com.client api 访问 MS word 文件的脚注。

I already googled, but I failed to find a proper way.我已经用谷歌搜索了,但我没有找到合适的方法。 I used python-docx for the above purpose but I found out that current version of python-docx could not access footnotes of MS Word file.我将 python-docx 用于上述目的,但我发现当前版本的 python-docx 无法访问 MS Word 文件的脚注。

As such, I am considering win32com.client api at present.因此,我目前正在考虑使用 win32com.client api。 I can find certain words in MS word document and replace them by using following codes.我可以在 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)

Part 1 in the above code works without any error but it cannot access footnotes.上述代码中的第 1 部分可以正常工作,但无法访问脚注。

Part 2 cannot find and replace words in footnotes, either.第 2 部分也无法找到和替换脚注中的单词。 Only an error message "NameError: name 'wdFootnotesStory' is not defined" appears.仅出现错误消息“NameError: name 'wdFootnotesStory' is not defined”。

I found a similar question and an answer to that in stackoverflow but the code in the answer does not work and same error message appears.我在 stackoverflow 中找到了一个类似的问题和答案,但答案中的代码不起作用,并且出现相同的错误消息。

Using Python to find and replace footnotes in word 使用Python在word中查找和替换脚注

It would be highly appreciated if someone lets me know how I can access footnote in MS word document.如果有人让我知道如何访问 MS Word 文档中的脚注,我将不胜感激。

I found a solution.我找到了解决方案。 Part 2 shall be changed as follows第 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