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

yipeiwu_com6年前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中列表和元组的使用方法和区别详解

一、二者区别 列表: 1.可以增加列表内容 append 2.可以统计某个列表段在整个列表中出现的次数 count 3.可以插入一个字符串,并把整个字符串的每个字母拆分当作一个列...

python使用xpath中遇到:<Element a at 0x39a9a80>到底是什么?

前言 大家在学习python爬虫的过程中,会发现一个问题,语法我看完了,说的也很详细,我也认真看了,爬虫还是不会写,或者没有思路,所以我的所有文章都会从实例的角度来解析一些常见的问题和...

PyCharm更改字体和界面样式的方法步骤

PyCharm更改字体和界面样式的方法步骤

更改主题 File → Settings → Appearance & Behavior → Appearance → Theme 结果: 更改字体大小 File → Sett...

python计算列表内各元素的个数实例

如下所示: list = [1,2,3,4,5,6,7,5,4,3,2,12] set = set(list) dict = {} for item in set: dict.u...

对python内置map和six.moves.map的区别详解

python内置map返回的是列表,而six.moves.map返回的是iter。 >>> map(lambda a: a*2, [1, 2, 3]) [2, 4,...