O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Passing Data In and Out

We put data into a cell with the Value property of a cell. We can also retrieve data the same way. This works with numbers and strings. Excel always stores numbers as floating-point values:

>>> xlSheet.Cells(1,1).Value = 'What shall be the number of thy counting?'
>>> xlSheet.Cells(2,1).Value = 3 
>>> xlSheet.Cells(1,1).Value
'What shall be the number of thy counting?'
>>> xlSheet.Cells(2,1).Value
3.0
>>>

Excel users know that dates are just numbers with formatting applied. However, Excel keeps track of which cells are known to be dates and which are ordinary numbers internally. Excel (and most Windows applications, as well as COM) define a date as the number of days since 1/1/1900, while Python (and Unix) counts the number of seconds. If you want to add a date, you can work out the number yourself, but the Python COM framework provides a utility to make a COM date, which ensures that it’s recognized properly but also accessible in Python format:

>>> import time
>>> now = time.time()
>>> now    # how many seconds since 1970?
923611182.35
>>> import pythoncom
>>> time_object = pythoncom.MakeTime(now)
>>> int(time_object)   # can get the value back...
923611182
>>> xlSheet.Cells(3,1).Value = time_object # ...or send it
>>> xlSheet.Cells(3,1).Value
<time object at 188c080>
>>>

When you send a date to Excel, it automatically formats the cell as well.

If you want to insert a formula, use the formula property and enter the formula exactly as you would in Excel:

>>> xlSheet.Cells(4,1).Formula ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required