python实现在windows下操作word的方法

本文实例讲述了python实现在windows下操作word的方法。分享给大家供大家参考。具体实现方法如下:

import win32com
from win32com.client import dispatch, constants
w = win32com.client.dispatch(‘word.application’)
# 或者使用下面的方法,使用启动独立的进程:
# w = win32com.client.dispatchex(‘word.application’)
# 后台运行,不显示,不警告
w.visible = 0
w.displayalerts = 0
# 打开新的文件
doc = w.documents.open( filename = filenamein )
# worddoc = 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)
# 表格操作
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 )
# 打印
doc.printout()
# 关闭
# doc.close()
w.documents.close(wc.wddonotsavechanges)
w.quit()

希望本文所述对大家的python程序设计有所帮助。

发表评论