import win32com
from win32com.client import Dispatch, constants
重要概念:
Application:WORD应用程序
Document: 一个打开的文档对象
Paragraph: 段落
ParagraphFormat: 段落格式
Section :代表指定文档、区域或所选文档中的节
w = win32com.client.Dispatch('Word.Application')
# 或者使用下面的方法,使用启动独立的进程:
# w = win32com.client.DispatchEx('Word.Application')
# 后台运行
w.Visible = 0 # 不显示
w.DisplayAlerts = 0 # 不警告
# 打开文件
doc = w.Documents.Open( FileName = filenamein ) # 打开已有文件
# doc = w.Documents.Add() # 创建新的文档
# 插入文字
myRange = doc.Range(0,0) # 两个参数分别代表起始点,结束点
myRange.InsertBefore('Hello from Python!')
# 使用样式
wordSel = myRange.Select()
wordSel.Style = constants.wdStyleHeading1
# 正文文字替换
w.Selection.Find.ClearFormatting()
w.Selection.Find.Replacement.ClearFormatting()
w.Selection.Find.Execute(OldStr, False, False, False, False, False, True, 1, True, NewStr, 2)
# 页眉文字替换
w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()
w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()
w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute(OldStr, False, False, False, False, False, True, 1, False, NewStr, 2)
# 在文档末尾新增一页并添加一个表格
pre_section = doc.Secitons(0)
new_seciton = doc.Range(pre_section.Range.End, pre_section.Range.End).Sections.Add()
new_range = new_seciton.Range
new_table = new_range.Tables.Add(doc.Range(new_range.End,new_range.End), 5, 5)
#在文档末尾添加一个5*5的表格
# 表格操作
doc.Tables[0].Rows[0].Cells[0].Range.Text ='123123'
worddoc.Tables[0].Rows.Add() # 增加一行
# 转换为html
wc = win32com.client.constants
w.ActiveDocument.WebOptions.RelyOnCSS = 1
w.ActiveDocument.WebOptions.OptimizeForBrowser = 1
w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
w.ActiveDocument.WebOptions.OrganizeInFolder = 0
w.ActiveDocument.WebOptions.UseLongFileNames = 1
w.ActiveDocument.WebOptions.RelyOnVML = 0
w.ActiveDocument.WebOptions.AllowPNG = 1
w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML )
# 增加10个新页,然后跳转到新页中增加内容
#(最好将其提取为一个函数)
section_index = 0
for i in range(0, 10):
pre_section = doc.Secitons(section_index)
new_seciton = doc.Range(pre_section.Range.End, pre_section.Range.End).Sections.Add()
new_range = new_seciton.Range
content_pg = new_range.Paragraphs.Add()
content_pg.Range.Font.Name,content_pg.Range.Font.Size = 'Times New Roman',24
caption_pg.Range.ParagraphFormat.Alignment = 0
# 0,1,2 分别对应左对齐、居中、右对齐
caption_pg.Range.InsertBefore('Hello,Page ' + str(i+1))
section_index += 1
doc.PrintOut() # 打印
# doc.Close() # 关闭
w.Documents.Close(wc.wdDoNotSaveChanges)
w.Quit()
一个批量修改页眉的代码
附上链接:python 使用win32com实现对word文档批量替换页眉页脚
两个修改word的代码
附上链接:
1.win32操作word
2.win32操作word