How To Read Excel Files In Python?

Tim Golden tim.golden at viacom-outdoor.co.uk
Tue Dec 13 05:27:02 EST 2005


[Anand]

> Can I get some help on how to read the excel files using python?

> from win32com.client import Dispatch
> xlApp = Dispatch("Excel.Application")
> xlWb = xlApp.Workbooks.Open("Read.xls")
> xlSht = xlWb.WorkSheets(1)

> But sadly, I am unable to proceed further about how 
> to read the cells of the worksheet of my excel file!

Well, I could (and doubtless others will) give you
some working code, but the code you give above must
come from somewhere -- some Microsoft example, or
a VBS repository, perhaps. Since you've already done
the only Python-specific part of the operation,
calling win32com.client.Dispatch, the rest is the
same in Python as in any other language.

However, to get you going...

<code>
import win32com.client

xlApp = win32com.client.gencache.EnsureDispatch ("Excel.Application")
xlWb = xlApp.Workbooks.Open ("c:/temp/temp.xls")
xlSht = xlWb.Worksheets (1)
for row in range (3):
  for col in range (3):
    print "(%d,%d) => %s" % (row, col, xlSht.Cells (1+row, 1+col).Value)

xlApp.Quit ()

</code>

NB There are several ways to do most of this. You could use,
for example, xlWb.ActiveSheet rather than Worksheets (1) etc.
Just go with whatever works for you.

Also, note that it's often useful to record what you want to
do as a macro within Excel, and then to look at the resulting
VBA to know what Python should be doing to achieve the same
result.

TJG

________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________



More information about the Python-list mailing list