欢迎来到山村网

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

2019-03-02 12:12:14浏览:453 来源:山村网   
核心摘要:  本文实例讲述了python实现在windows下操作word的方法。分享给大家供大家参考。具体实现方法如下:  ? 1234567891011121314

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

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 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程序设计有所帮助。

(责任编辑:豆豆)
下一篇:

介绍Python的@property装饰器的用法

上一篇:

python使用urllib2实现发送带cookie的请求

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com