本文实例讲述了python实现在windows下操作word的方法。分享给大家供大家参考。具体实现方法如下:
import win32comfrom win32com.client import dispatch, constantsw = win32com.client.dispatch('word.application')# 或者使用下面的方法,使用启动独立的进程:# w = win32com.client.dispatchex('word.application')# 后台运行,不显示,不警告w.visible = 0w.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() # 增加一行# 转换为htmlwc = win32com.client.constantsw.activedocument.weboptions.relyoncss = 1w.activedocument.weboptions.optimizeforbrowser = 1w.activedocument.weboptions.browserlevel = 0 # constants.wdbrowserlevelv4w.activedocument.weboptions.organizeinfolder = 0w.activedocument.weboptions.uselongfilenames = 1w.activedocument.weboptions.relyonvml = 0w.activedocument.weboptions.allowpng = 1w.activedocument.saveas( filename = filenameout, fileformat = wc.wdformathtml )# 打印doc.printout()# 关闭# doc.close()w.documents.close(wc.wddonotsavechanges)w.quit()
希望本文所述对大家的python程序设计有所帮助。