Embedding objects( txt, doc) into excel using python

Tim Golden mail at timgolden.me.uk
Thu May 31 04:42:44 EDT 2007


Girish wrote:

> I want to embed  a txt document into an excel using python.

I didn't know people still did that! Still, each to
his own ;)

> Here is my code, but i get an error message
> ===================================================
> Traceback (most recent call last):
>   File "C:\Documents and Settings\kusumap\Desktop\Girish.py", line 7,
> in ?
>     worksheet.OLEObjects.Add(Filename="C:\Documents and Settings
> \kusumap\My Documents\desktop.ini", Link=False,DisplayAsIcon=True,
> IconFileName="packager.exe", IconIndex=0, IconLabel="C:\Documents and
> Settings\kusumap\My Documents\desktop.ini").Select
> AttributeError: 'function' object has no attribute 'Add'
> ===================================================

Well done for providing reproducible code, by the way.
It's amazing how many people expect us to deduce code
from tracebacks! Two things:

1) You need to use raw strings for your path names
or to double-up the slashes. By good fortune, you
don't seem to be using any actual special characters
(\n, \r, \t etc.) but you won't always be so lucky!

2) As the error suggests, OLEObjects is in fact a method,
not an container. Slightly more concise screen dump:

<dump>
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more 
information.
 >>> import win32com.client
 >>> xl = win32com.client.Dispatch ("Excel.Application")
 >>> ws = xl.Workbooks.Add ().ActiveSheet
 >>> print repr (ws.OLEObjects)
<bound method _Worksheet.OLEObjects of 
<win32com.gen_py.Microsoft Excel 11.0 Object 
Library._Worksheet instance at 0x24646440>>
 >>>
 >>> o = ws.OLEObjects ()
 >>> o
<win32com.gen_py.Microsoft Excel 11.0 Object 
Library.OLEObjects instance at 0x24648240>
 >>> o.Add
<bound method OLEObjects.Add of <win32com.gen_py.Microsoft 
Excel 11.0 Object Library.OLEObjects instance at 0x24648240>>
 >>>
</dump>

As you can see, the ws.OLEObjects is a bound method,
ie a function within the _Worksheet class. It seems
to return a value which is an OLEObjects instance,
which itself seems to have an .Add method. Although
I could forage in the docs, I just tried it out at
the interpreter. You can do the same if you want!

TJG



More information about the Python-list mailing list