python实现在windows下操作word的方法
更新时间:2015年04月28日 09:48:39 作者:重负在身
这篇文章主要介绍了python实现在windows下操作word的方法,涉及Python操作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程序设计有所帮助。
相关文章
Python通过Manager方式实现多个无关联进程共享数据的实现
这篇文章主要介绍了Python通过Manager方式实现多个无关联进程共享数据的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-11-11Pandas分组聚合之使用自定义函数方法transform()、apply()
Pandas具有很多强大的功能,transform就是其中之一,利用它可以高效地汇总数据且不改变数据行数,下面这篇文章主要给大家介绍了关于Pandas分组聚合之使用自定义函数方法transform()、apply()的相关资料,需要的朋友可以参考下2023-01-01Django User 模块之 AbstractUser 扩展详解
这篇文章主要介绍了Django User 模块之 AbstractUser 扩展详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-03-03
最新评论