Calling Python functions from Excel

C

Chris Withers

Mark said:
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
 
M

Mark Tolonen

Chris Withers said:
...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
 
C

Cannonbiker

Mark Tolonen wrote:
...and it's generally accepted that COM sucks rocks through straws, so
explore alternatives when they're available ;-)

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

Thanks very much. It works perfectly!!! :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top