1、添加多级标题
import win32com.client as win32
from win32com.client import constants
doc_app = win32.gencache.EnsureDispatch('Word.Application')#打开word应用程序
doc_app.Visible =1#设置应用程序可见
doc = doc_app.Documents.Add()#创建新得文档
#添加标题1
##添加文字
parag = doc.Paragraphs.Add()#添加新得段落
parag_range = parag.Range
parag_range.Text ='标题1'
###设置样式
parag_range.Style = doc.Styles("Heading 1")#Heading 1 是样式的名称
border = parag.Borders(constants.wdBorderBottom)
border.LineStyle = constants.wdLineStyleSingle
border.LineWidth = constants.wdLineWidth225pt
#添加标题2
parag_range.Text +='\n'
parag = doc.Paragraphs.Add()
parag_range = parag.Range
parag_range.Text ='标题2'
parag_range.Style = doc.Styles("Heading 2")#二级标题
##添加正文
parag_range.Text +='\n'
parag = doc.Paragraphs.Add()
parag_range = parag.Range
parag_range.Text ='正文'
parag_range.Style = doc.Styles("Normal")#正文
使用add不会添加新的一个段落,而是指向当前所在的段落。
2、插入目录
import win32com.client as win32
from win32com.client import constants
doc_app = win32.gencache.EnsureDispatch('Word.Application')
doc_app.Visible =1
doc = doc_app.Documents.Add()
#添加标题1
##添加文字
parag = doc.Paragraphs.Add()
parag_range = parag.Range
parag_range.Text ='标题1'
###设置样式
parag_range.Style = doc.Styles("Heading 1")#Heading 1 是样式的名称
border = parag.Borders(constants.wdBorderBottom)
border.LineStyle = constants.wdLineStyleSingle
border.LineWidth = constants.wdLineWidth225pt
#添加标题2
parag_range.InsertParagraphAfter()#在当前位置之后,新插入一行
parag_range = parag.Range
parag_range.Text ='标题2'
parag_range.Style = doc.Styles("Heading 2")#二级标题
##添加正文
parag_range.InsertParagraphAfter()
parag_range = parag.Range
parag_range.Text ='正文'
parag_range.Style = doc.Styles("Normal")#正文
##插入目录
##parag_range = doc.Paragraphs(1)##找到第一行
doc.Paragraphs(1).Range.InsertParagraphBefore()#在首行之前插入一行,用于插入目录
parag_range = doc.Paragraphs(1).Range#指向新插入的行
#插入目录
##从当前指向的位置插入目录,使用默认样式设置目录样式,包含3级标题
doc.TablesOfContents.Add(Range=parag_range, UseHeadingStyles=True,LowerHeadingLevel=3)
3、插入页眉
import win32com.client as win32
from win32com.client import constants
doc_app = win32.gencache.EnsureDispatch('Word.Application')
doc_app.Visible =1
doc = doc_app.Documents.Add()
#添加页眉
##添加文字
doc.PageSetup.DifferentFirstPageHeaderFooter = True
wd_section = doc.Sections(1)#注意section内部成员编号是从1开始的
hdr_rng = wd_section.Headers.Range
hdr_rng.Font.ColorIndex = constants.wdDarkRed
hdr_rng.Font.Size = 20
hdr_rng.Text = 'test text'
hdr_rng.InsertBefore('test text11')
关于插入的header的常量的解释:wdHeaderFooterEvenPages:Returns all headers or footers on even-numbered pages.
wdHeaderFooterFirstPage:Returns the first header or footer in a document or section.
wdHeaderFooterPrimary:Returns the header or footer on all pages other than the first page of a document or section.
使用wdHeaderFooterFirstPage,只会在第一页添加页眉页脚,使用wdHeaderFooterPrimary则会在除了第一页之外的页增加页眉页脚。
备注;如果本文有帮助,欢迎点赞(。ò ∀ ó。)