2017-03-09 94 views
0

我試圖以編程方式編寫一個Word文件,並努力在選擇對象上交替樣式。這裏是代碼的相關位:win32com在選擇對象中的樣式之間移動

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. 

看來,我的「選擇」然而,影響所有的文件,當我做我的初步objSel.Style分配「標題3」之前的線都沒有影響。當我切換回正常時,其他一切都是。

回答

0

看來,我需要做的(或將解決這個問題的事情至少一個)是添加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) 

這會在正確的標題下顯示數據,然後在下一行顯示正常類型的文本。