python在windows下操作word的方法
发布时间:2020-12-17 17:19:55 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 import win32comfrom win32com.client import Dispatch,constants w = win32com.client.Dispatch('Word.Application')# 或者使用下面的方法,使用启动
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 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,True,1,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,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() 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |