win32com Tricks and Secrets The essential tools for using com objects in Python Presented by Craig Miller [email protected] Utah Division of Water Resources November 9, 2010
Feb 24, 2016
win32com Tricks and SecretsThe essential tools for using com objects in Python
Presented by Craig [email protected] Division of Water Resources
November 9, 2010
What Tricks (you might ask)Create reports with WordCreate tables, charts, graphicsUse any database accessible
through ADODB.Translate existing VB, C+ into
python to use the same com objects
Etc.
Download/Install Pythonwin Navigate to http://sourceforge.net/projects/pywin32/
Select this
To view this
Computer/System
Python version
Where is PythonWin installed?ArcGIS 10 setup
Basic example (will work after install)Import win32com.client xlApp = win32com.client.Dispatch(
"Excel.Application")xlApp.Visible = TruexlApp.WorkBooks.Add()
Note: Should show Excel with 3 standard worksheets, sheet1, sheet2, sheet3
What Strings to Use with DispatchDo not use Task Manager to find
strings. Old help suggests this but now doesn’t work.
For Word use “Word.Application”For other applications use
MakePy
Create them with MakePy
Select your Com objects and press
“OK”results below
Look at Code in Script
Where to get helpCreate macros and translate the
code from Word or Excel.Use .chm helpfiles from
Microsoft, for example vbalx10.chm for excel.
Use ADO210.CHM for ADODB
Use JETSQL40.chm for SQL
More .chm files are available
What you get after DispatchNote: This only works in PythonWin
You can now inspect xlApp’s methods
Rules are for following!If you use MakePy
◦…. and distribute your code, distribute the files created by MakePy.
Suggestions for modifying VBA to work in python:Case for methods and attributes matters.
RS.MoveFirst() not RS.movefirst()Always use () with methods
RS.MoveFirst() not RS.MoveFirstAttributes or values don’t need ()
◦while not RS.EOF: acceptableDon’t use shortcuts! (Use PythonWin here)
RS.Fields(“ID”).Value not RS(“ID”)
If you use MakePyMake sure that you also include
the proper COM files if you use a specific version.
Consider using generic versions by simply deleting the version number, ie. “ADODB.Connection” not “ADODB.Connection.6.0”
HintsDevelop initial code in VB, C+, or
C++Can integrate python and ruby
into Visual Studio 2010. Less need for these workarounds when VS 2010 is standard for ArcGIS.
You can integrate python into microsoft code now if you register it!
Need More Help??
Thank You!Questions?Email: [email protected]: 801-538-7280