直接上python3.6中代码
[Python] 纯文本查看 复制代码
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#coding:utf-8# python操作wordfrom tkinter import Tkfrom time import sleepfrom tkinter.messagebox import showwarningimport win32com.client as winwarn = lambda app: showwarning(app, 'Exit?') # 弹出提示框def word(): app = 'Word' word = win.gencache.EnsureDispatch('%s.Application' % app) # 创建word对象 doc = word.Documents.Add() #添加一个文档 word.Visible = True #设置为桌面显示可见 sleep(1) #暂停一秒,让用户看清演示的每一步 rng = doc.Range(0,0) # 定位光标位置 rng.InsertAfter('first line\r\n\r\n') # 在光标后加入内容 sleep(1) for i in range(3, 10): rng.InsertAfter('Line %d\r\n' % i) # 在光标后加入内容 sleep(1) rng.InsertAfter("\r\nlast line\r\n") # 在光标后加入内容 warn(app) # 弹出警告消息# doc.Save("test.doc") # 保存 doc.Close(False) # 关闭 word.Application.Quit() # word应用退出if __name__=='__main__': Tk().withdraw() # 不让tk顶级窗口出现,因为默认tk会自动创建一个顶级窗口,而且不会将其隐藏 word()
|