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程序设计有所帮助。

相关文章

pytorch 把MNIST数据集转换成图片和txt的方法

本文介绍了pytorch 把MNIST数据集转换成图片和txt的方法,分享给大家,具体如下: 1.下载Mnist 数据集 import os # third-party librar...

Python中的引用和拷贝浅析

If an object's value can be modified, the object is said to be mutable. If the value cannot b...

python批量修改图片尺寸,并保存指定路径的实现方法

如下所示: import os from PIL import Image filename = os.listdir("D:\\Work\\process\\样本处理\\pol...

Django在Win7下的安装及创建项目hello word简明教程

python广受欢迎的编程语言之一,本文简述了python 的django 框架安装与开发。 Django在Win7下的安装及创建项目hello word,相对而言非常简单,这里直接给出...

python3 selenium自动化 下拉框定位的例子

python3 selenium自动化 下拉框定位的例子

我们在做web UI自动化时,经常会碰到下拉框,如下图: 所上图,下拉框的源代码如下: <html1> <head></head> <...