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

yipeiwu_com5年前Python基础

本文实例讲述了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中__str__和__repr__方法的区别

 对我当前工程进行全部测试需要花费不少时间。既然有 26 GB 空闲内存,为何不让其发挥余热呢? tmpfs 可以通过把文件系统保存在大内存中来加速测试的执行效率。 但...

Python+Wordpress制作小说站

我用Python和Wordpress建了一个小说站。 下面主要讲一讲搭建过程中所用的技术。主要分为以下几个部分: Wordpress主题的选取 小说内容的完善 站点的部署...

Python splitlines使用技巧

复制代码 代码如下:mulLine = """Hello!!! Wellcome to Python's world! There are a lot of interesting th...

python 排序算法总结及实例详解

python 排序算法总结及实例详解

总结了一下常见集中排序的算法 归并排序 归并排序也称合并排序,是分治法的典型应用。分治思想是将每个问题分解成个个小问题,将每个小问题解决,然后合并。 具体的归并排序就是,将一组无序数...

Python3实现将本地JSON大数据文件写入MySQL数据库的方法

本文实例讲述了Python3实现将本地JSON大数据文件写入MySQL数据库的方法。分享给大家供大家参考,具体如下: 最近导师给了一个yelp上的评论数据,数据量达到3.55个G,如果进...