简体   繁体   English

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

[英]How to center text in MS Word with Python win32com

I'm automating the creation of an MS Word document and part of the code utilizes win32com to update the table of contents and the header. 我正在自动创建MS Word文档,部分代码利用win32com更新了目录和标题。 The function that does this looks like this: 执行此操作的函数如下所示:

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)

This seems to work fine. 这似乎很好。 The problem is that when the header text gets replaced, for some reason, the header gets left justified, instead of being centered the way it was before I changed the header text. 问题在于,由于某些原因替换标题文本时,标题会保持对齐,而不是像我更改标题文本之前那样居中。

Does somebody know how to 有人知道如何

  1. Prevent this left justification from happening and/or 防止这种左对齐的情况发生和/或
  2. Center the text again after the text has changed? 文本更改后再次居中文本?

Summarizing the results of the comments section, there is no way for win32com to center text in a header. 总结注释部分的结果,win32com无法将文本置于标题中。 The solution, at least in this case, was to make sure that the formatting in the document was correct on ALL modified lines before trying to modify the text. 至少在这种情况下,解决方案是在尝试修改文本之前,确保所有修改行上的文档格式均正确。 If your application requires you to modify text, then change the formatting (center, left-justified, etc.) after that header text is changed, win32com can't help...at least today. 如果您的应用程序要求您修改文本,然后在更改标题文本后更改格式(居中,左对齐等),则Win32com至少在今天还是无济于事。

Using the the .Paragraphs.Alignment property of the header object as defined below can indeed align the header. 使用下面定义的标头对象的.Paragraphs.Alignment属性确实可以对齐标头。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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