win32com 在选择中的样式之间移动

win32com moving between Styles in a Selectoin

我正在尝试以编程方式编写一个 Word 文件,但我正在努力改变选择对象的样式。这是相关的代码:

objWord = win32com.client.Dispatch("Word.Application")
objSel = objWord.Selection
writestuff = "\r\nSome Heading"
objSel.Style = objWord.ActiveDocument.Styles("Heading 3")
objSel.TypeText(writestuff)
#This works so far, we have a heading and some text, now we want to write data below the heading
objSel.Style = objWord.ActiveDocument.Styles("Normal") #Setting style back to 'Normal' for next section
writestuff = "\r\nSome data about the heading we just wrote") 
objSel.TypeText(writestuff)
#At this point the heading and new text both go to the 'Normal' style.

我的 'selection' 似乎影响了所有文档,但是,当我对 'Heading 3' 进行初始 objSel.Style 分配时,之前的行没有受到影响。当我切换回正常时,其他一切都是。

看来我需要做的(或者至少是解决这个问题的事情之一)是添加一个 TypeParagraph() 方法

更正后的代码如下所示:

objWord = win32com.client.Dispatch("Word.Application")
objSel = objWord.Selection
writestuff = "\r\nSome Heading"
objSel.Style = objWord.ActiveDocument.Styles("Heading 3")
objSel.TypeText(writestuff)
objSel.TypeParagraph ##THIS IS WHAT I ADDED, NO NEED TO READJUST STYLE##
writestuff = "\r\nSome data about the heading we just wrote") 
objSel.TypeText(writestuff)

这将显示带有正确标题的数据,然后 normal-type 在下一行显示文本。