[Python]win32com模块编程初探

来源:互联网 发布:阿里云邮寄资料 编辑:程序博客网 时间:2024/05/17 04:45

1,Excel

#! /usr/bin/env python#coding=utf-8from Tkinter import Tkfrom time import ctimefrom tkMessageBox import showwarningimport win32com.client as win32warn = lambda app:showwarning(app,'exit?')RANGE  = range(3,8)def excel():    app = 'Excel'    xl = win32.Dispatch('%s.Application'%app)    ss = xl.Workbooks.Add()    sh = ss.ActiveSheet    xl.Visible = True    sh.Cells(1,1).Value = 'Python-to-%s Demo'%app        for i in RANGE:        sh.Cells(i,1).Value = 'Line %d'%i    sh.Cells(i+2,1).Value = 'Are you kidding me?'        warn(app)    ss.Close(False)    xl.Application.Quit()    if __name__ == '__main__':    Tk().withdraw()    excel()        


2,Word

#! /usr/bin/env python#coding=utf-8from Tkinter import Tkfrom time import ctimefrom tkMessageBox import showwarningimport win32com.client as win32warn = lambda app:showwarning('%s.Application'%app,'Exit?')def word():    app = 'Word'    word = win32.Dispatch('%s.Application'%app)    doc = word.Documents.Add()    word.Visible = True        rng = doc.Range(0,0)    rng.InsertAfter('Python-to-%s Demo\r\n\r\n'%app)           for i in range(3,8):        rng.InsertAfter('Line %i\r\n'%i)            rng.InsertAfter('\r\nAre you kidding me?\r\n')    warn(app)    doc.Close(False)    word.Application.Quit()    if __name__ == "__main__":    Tk().withdraw()    word()    

3,PowerPoint

#! /usr/bin/env python#coding=utf-8from Tkinter import Tkfrom tkMessageBox import showwarningimport win32com.client as win32from time import sleepwarn = lambda app:showwarning('%s.Application'%app,'Exit?')def ppt():    app = 'PowerPoint'    ppoint = win32.gencache.EnsureDispatch('%s.Application'%app)    pres = ppoint.Presentations.Add()    ppoint.Visible = True        s1 = pres.Slides.Add(1,win32.constants.ppLayoutText)    sleep(1)    print '\n'.join(dir(s1.Shapes))    itr = iter(s1.Shapes)    s1a = itr.next().TextFrame.TextRange    #s1a = s1.Shapes[0].TextFrame.TextRange    s1a.Text = 'Python-to-%s Demo'%app        #s1b = s1.Shapes[1].TextFrame.TextRange    s1b = itr.next().TextFrame.TextRange    for i in range(3,8):        s1b.InsertAfter('Line %d\r\n'%i)            s1b.InsertAfter('\r\nAre you kidding me?\r\n')        warn(app)    pres.Close()    ppoint.Quit()    if __name__ == '__main__':    Tk().withdraw()    ppt()        


REF:Core Programming Python


0 0