Thursday, December 18, 2008

Python and Excel

Python and Excel: "Integrating Python and MS Excel

Basic example

# this example starts Excel, creates a new workbook,
# puts some text in the first and second cell
# closes the workbook without saving the changes
# and closes Excel. This happens really fast, so
# you may want to comment out some lines and add them
# back in one at a time ... or do the commands interactively


from win32com.client import Dispatch


xlApp = Dispatch('Excel.Application')
xlApp.Visible = 1
xlApp.Workbooks.Add()
xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
xlApp.ActiveWorkbook.Close(SaveChanges=0) # see note 1
xlApp.Quit()
xlApp.Visible = 0 # see note 2
del xlApp

# raw_input('press Enter ...')


Notes

1. I changed xlApp.Close(SaveChanges=0) to xlApp.ActiveWorkbook.Close(SaveChanges=0), because I was advised that the former didn't work.
2. On 14-Feb-2006, Stef Cruz informed me: 'I find that you must make x1App.Visible=0 before you use del x1App, otherwise EXCEL.EXE remains in memory. Try out the code again with Task Manager running, you'll see what I mean.'"

No comments: