Home » excel » Documentation for Excel python COM object?

Documentation for Excel python COM object?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I want to use Python and COM to manipulate data and formula in Excel files. I’ve looked around a couple of modules in python but I have yet to find support for reading formulas. So I am forced to use COM. I’m not sure what to call it but is there something like a documentation for all the classes and methods available on python,COM for excel. There are a few sample codes here and there but I can’t seem to find any exhaustive documentation for what I want to do.

import win32com
import win32com.client
xl = win32com.client.Dispatch("Excel.application")
xl.__doc__

I thought the last line would print a list of methods or documentation for the Excel application

sel = xl.Selection

Selection() method above does not display when I hit TAB after xl. I just know there is a Selection method because I read it from a pyxll sample module. So I assume there’s more methods out there that’s not included in the TAB menu.

sel.Value = "Hello!"
sel.font.bold = true

Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
sel.font.bold = true
NameError: name 'true' is not defined

sel.font.bold = 1
sel.font = "Constantia"

Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
sel.font = "Constantia"
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 570, in  __setattr__
raise AttributeError("Property '%s.%s' can not be set." % (self._username_, attr))
AttributeError: Property '<unknown>.font' can not be set.

So I’m guessing around with this but I want to learn with a proper documentation so I know what objects/methods are available to me. Can anyone point me to the right direction? Thanks in advance!

How to&Answers:

We struggled with these interfaces recently. Try working from the help pages on the Microsoft website.

The examples are in C# / VB.NET so it helps if you know one of those languages… Have fun! 🙂

Answer:

True is case sensitive: sel.font.bold=True works.

Font can be set to Constantia like this: sel.font.Name="Constantia".

I’m not aware of any PythonCOM documentation either, but the interface pretty much translates the Visual Basic properties to Python, so you can just follow the VBA documentation, in many cases the VBA code works almost verbatim, of course you have to change VBA boilerplate and control structures to their Python equivalents.