Adding Worksheets to an Excel Workbook

wesley chun wescpy at gmail.com
Wed Oct 11 15:07:20 EDT 2006


> From: e.h.doxtator at accenture.com
> Date: Tues, Oct 10 2006 2:08 pm
>
> I'm a Python newbie, and I'm just getting to the wonders of COM
> programming.


welcome to Python!!  i too, have (recently) been interested in COM
programming, so much so that i added some material on Microsoft Office
(Win32 COM Client) Programming to the 2nd ed of my book, "Core Python
Programming" (see link below).  it's only introductory material, but i
think you may find it useful as i have, and shows you how to create
simple applications for Excel, Word, PowerPoint, and Outlook.

in addition to greg's code snippet, here's a snippet based on one from
the book (the code is under a CC license) -- it doesn't add a new
sheet, but does let you grab the "active" one (the one that is tabbed
and facing the user):

# based on excel.pyw in Core Python Programming, 2nd ed

from time import sleep
import win32com.client as win32

def excel():
    xl = win32.gencache.EnsureDispatch('Excel.Application')
    ss = xl.Workbooks.Add() # add a new spreadsheet/workbook
    sh = ss.ActiveSheet  # grab the active sheet of the workbook
    xl.Visible = True        # make Excel show up on the desktop
    sleep(1)

    sh.Cells(1,1).Value = 'Python-to-Excel Demo'
    sleep(1)
    for i in range(3, 8):
        sh.Cells(i,1).Value = 'Line %d' % i
        sleep(1)
    sh.Cells(i+2,1).Value = "Th-th-th-that's all folks!"

    sleep(5)
    ss.Close(False) # close the workbook and don't save
    xl.Application.Quit() # quit Excel

if __name__=='__main__':
    excel()

hope this helps!
-wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com



More information about the Python-list mailing list