简体   繁体   中英

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.

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.

As such, I am considering win32com.client api at present. I can find certain words in MS word document and replace them by using following codes.

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.

Part 2 cannot find and replace words in footnotes, either. Only an error message "NameError: name 'wdFootnotesStory' is not defined" appears.

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.

Using Python to find and replace footnotes in word

It would be highly appreciated if someone lets me know how I can access footnote in MS word document.

I found a solution. Part 2 shall be changed as follows

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM