Calling Python functions from Excel

Mark Tolonen metolone+gmane at gmail.com
Tue Nov 17 21:09:13 EST 2009


"Chris Withers" <chris at simplistix.co.uk> wrote in message 
news:4B02D1E3.6080308 at simplistix.co.uk...
> Mark Tolonen wrote:
>>
>>>> Please I need Calling Python functions from Excel and receive result
>>>> back in Excel. Can me somebody advise simplest solution please? I am
>>>> more VBA programmer than Python.
>>>
>>> Try http://code.google.com/p/pyinex/
>>
>> The book Python: Programming on Win32 has a whole chapter on COM, and a 
>> section on COM servers.
>
> ...and it's generally accepted that COM sucks rocks through straws, so 
> explore alternatives when they're available ;-)
>
> Chris

True, but as usual Python makes it pretty darn easy (requires PyWin32):

------------- ex.py -------------------------------
class Example(object):
    _public_methods_ = ['Add','Mul']
    _reg_progid_ = 'MyPython.Example'
    _reg_clsid_ = '{insert_GUID_here}'

    def Add(self,a,b):
        return a+b

    def Mul(self,a,b):
        return a*b

if __name__ == '__main__':
    import win32com.server.register
    win32com.server.register.UseCommandLine(Example)
---------------------------------------------------------

-------------- Excel Macro ----------------------
Sub Testit()
    Set ex = CreateObject("MyPython.Example")
    Range("A1") = ex.Add(1, 2)
    Range("A2") = ex.Mul(3, 4)
End Sub
--------------------------------------------------------

Just run the script to register the server.  "ex.py --unregister" will 
remove it.

-Mark





More information about the Python-list mailing list