Editing MS Word header with win32com

2019-07-14 05:37发布

I'm trying to edit header of a MS Word document that has existing header using win32com.
I tried this to edit page header:

import win32com.client as win32

word = win32.gencache.EnsureDispatch('Word.Application')
doc=word.Documents.Open("C:\\a.docx")
word.Visible = True
word.ActiveDocument.Sections[0].Headers[win32.constants.wdHeaderFooterPrimary].Range.Text='test text'
word.ActiveDocument.Save()
doc.Close(False)
word.Application.Quit()

But it has no effect (header didn't changed at all)!!
What is the correct way to edit MS Word header via win32com ?

1条回答
萌系小妹纸
2楼-- · 2019-07-14 06:24

Use parentheses instead of square brackets in this line, along with 1-based indexing. Everything in COM is a function call or property.

word.ActiveDocument.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range.Text='test text'
查看更多
登录 后发表回答