convert COM obj to integer

Bell, Kevin kevin.bell at slcgov.com
Wed Nov 2 15:59:43 EST 2005


I'm pulling a range of cells from Excel into a list and the data in
Excel is a number or possibly some text like an asterisk.  Each member
of the list is a com object (I think) and I'm converting them to
integers (or to None if not numberic) but my method seems very silly.
Is this the best way to go about it?  

It does exactly what it should, but it seems like a lot of extra BS to
convert my object to a string to a float to a rounded integer!  Don't
laugh.  I'm new at this!


THE SCRIPT:----------------------------------

import win32com.client
xlApp = win32com.client.Dispatch("Excel.Application")
f = r"C:\py\TrafficVolumes\xlTestDocs\3125113A.xls"
xlApp.Visible = 0
xlApp.Workbooks.Open(f)
list = xlApp.ActiveWorkbook.ActiveSheet.Range("Q13:Q36")

print list
print "\n"


def comObjToInteger(myObj):
    try:
        s = str(myObj)
        fl = float(s)
        integer = int(round(fl))
        return integer
    except:
        return None


for i in list:
    print comObjToInteger(i)


xlApp.ActiveWorkbook.Close(SaveChanges=0)
xlApp.Quit()

del xlApp #clean up
----------------------------------------------

THE RESULT:--------------------

>>> the list:
((4.7999999999999998,), (u'*',), (2.0,), (1.6000000000000001,),
(5.5999999999999996,), (19.399999999999999,), (25.0,),
(38.799999999999997,), (32.799999999999997,), (21.0,), (24.0,),
(17.399999999999999,), (22.800000000000001,), (22.600000000000001,),
(33.799999999999997,), (35.399999999999999,), (29.199999999999999,),
(35.399999999999999,), (32.200000000000003,), (26.0,),
(24.399999999999999,), (22.800000000000001,), (14.0,), (11.6,))

my converted values:
5
None
2
2
6
19
25
39
33
21
24
17
23
23
34
35
29
35
32
26
24
23
14
12
----------------------------------




More information about the Python-list mailing list