如何使用 Python win32com 将 MS Word 中的文本居中

How to center text in MS Word with Python win32com

我正在自动创建 MS Word 文档,部分代码利用 win32com 更新内容 table 和 header。执行此操作的函数如下所示:

import win32com.client as win32

def updateHeaderAndTOC(docx_file, headerText):
    word = win32.gencache.EnsureDispatch("Word.Application")
    doc = word.Documents.Open(docx_file)
    word.ActiveDocument.Sections(1)\
        .Headers(win32.constants.wdHeaderFooterPrimary)\
        .Range.Text=headerText
    doc.TablesOfContents(1).Update()
    doc.Close(SaveChanges=True)

这似乎工作正常。问题是当 header 文本被替换时,出于某种原因,header 左对齐,而不是像我更改 header 文本之前那样居中。

有人知道如何

  1. 防止这种左对齐的情况发生and/or
  2. 文本更改后再次居中?

总结一下评论区的结果,win32com 没办法让文字居中header。至少在这种情况下,解决方案是在尝试修改文本之前确保文档中 ALL 修改行的格式正确。如果您的应用程序要求您修改文本,然后在 header 文本更改后更改格式(居中,left-justified 等),win32com 无能为力...至少在今天。

使用下面定义的 header object 的 .Paragraphs.Alignment 属性 确实可以对齐 header.

import win32com.client

wrdApp = win32com.client.Dispatch('Word.Application')
doc = wrdApp.Documents.Open(fullFilePathAndName, False)
header = doc.Sections(1).Headers(win32com.client.constants.wdHeaderFooterPrimary).Range
header.Text = "some new header goes here"

#this will align the header content
header.Paragraphs.Alignment = win32com.client.constants.wdAlignParagraphCenter