天天看点

[Python]win32com模块编程初探

1,Excel

#! /usr/bin/env python
#coding=utf-8

from Tkinter import Tk
from time import ctime
from tkMessageBox import showwarning
import win32com.client as win32

warn = 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()
    
    
           
[Python]win32com模块编程初探

2,Word

#! /usr/bin/env python
#coding=utf-8

from Tkinter import Tk
from time import ctime
from tkMessageBox import showwarning
import win32com.client as win32

warn = 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()
    
           
[Python]win32com模块编程初探

3,PowerPoint

#! /usr/bin/env python
#coding=utf-8

from Tkinter import Tk
from tkMessageBox import showwarning
import win32com.client as win32
from time import sleep

warn = 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()
    
    
           
[Python]win32com模块编程初探

REF:Core Programming Python