from win32com.client import Dispatch
client = Dispatch('kwps.Application')
#client = Dispatch('word.Application')
client.Visible = 1 # or True
d1 = client.Documents.Open(FileName = " ",
ConfirConversion = True, #提示用户如果不是word文档 是否强制转换
ReadOnly = False, #是否是只读方式打开
AddToRecentFiles = True, #是否添加至最近打开列表
PasswordDocument = " " #加密文档的密码
)
d2 = client.Documents.Add(" ")
client.Documents.close() #自动保存
#访问第一个 即d1 client.Documents[0]
client.Quit()
一、Application
Dispatch是最基础的调度器,其余两个都是基于其的封装。
- Dispatch 在运行的时候,会自动检测本地是否有启动的word客户端,如果有启动的它将会接管,反之会创建一个客户端。
- DispatchEx 一旦运行就创建一个新的客户端出来。
- EnsureDispatch 运行的时候会在本地生成一个关于win32com的Python接口文件,也生成了word编程中所用到的大量的常量。
1、打开客户端:win32com.client.Dispatch
Visible设置客户端是否可见。
2、退出客户端:Application.Quit()
二、Documents
1、属性
Count:统计当前Documents容器中共打开了多少文档
item:使用索引访问Documents容器中的某个文档,返回一个Document对象,如item(1)
Application:返回Application对象(Documents的父级对象),借助该对象,Documents可使用父级对象的属性和方法
2、方法
Add:创建一个文档,返回一个Document对象,并将该对象加入到Documents容器中
Open:打开一个文档,返回一个Document对象,并将该对象加入到Documents容器中
Close:关闭容器中所有文档
Save:保存容器中所有文档
