COM Client problem with Excel

Blair Hall b.hall at irl.cri.nz
Sun Jul 7 17:51:41 EDT 2002


I am not sure how to handle Python exceptions when my Python
program is using Excel as a client.

At present, if anything raises
a Python exception while I have an active reference to Excel, then the
behaviour of the Python-Excel link is damaged until I close Pythonwin
and start
all over again (worse it is sometimes necessary to reboot).

At the end of this message  is some code that will cause the problem to
occur (by calling the 'problem' function). I.e.

>>> xl = Excel('test')
>>> xl.problem()

If I then try

>>> xl = Excel("test2")

for example, I will get only part of the Excel toolbar on screen, or
perhaps
Excel will not start properly, or something else will be wrong...

I  am using win95 with the latest version of Python and the windows
extensions.

What should I be doing to keep Excel happy? Indeed, where should I be
looking
to find out how to write more stable Com-Python code?

import win32com.client
import pythoncom

def comExceptionHandler(hr,msg,exc,arg) :
    print 'COM call failed: %s' % msg
    if exc is not None:
        wcode, source, text, helpFile, helpID, scode = exc
        print 'Error source:',source
        print text
        print 'See also: %s (id=%d)' % (helpFile,helpID)

class Excel:
    def __init__(self,filename,visible=1):
        """
        Create a new file in the current working directory
        and save a new Excel workbook in it.
        """
        import os
        filename = os.path.join( os.getcwd(), filename )
        try:
            self.app = win32com.client.Dispatch("Excel.Application")
            wb = self.app.Workbooks.Add()
            wb.SaveAs(filename)
            wb.Activate()
            self.app.Visible = visible
        except pythoncom.com_error, (hr,msg,exc,arg):
            comExceptionHandler(hr,msg,exc,arg)

    def __del__(self):
        wb = self.app.ActiveWorkbook
        wb.Save()
        self.app.Quit()

    def problem(self):
        raise "something"





More information about the Python-list mailing list