How do I read Excel file in Python?

John Machin sjmachin at lexicon.net
Thu Oct 5 17:21:58 CEST 2006


kath wrote:
> How do I read an Excel file in Python?
>
> I have found a package to read excel file, which can be used on any
> platform.

Hi Sudhir,
So far, so good :-)

>
> http://www.lexicon.net/sjmachin/xlrd.htm
> I installed and working on the examples, I found its printing of cell's
> contents in a different manner.
>
> >>> import xlrd
> >>> book=xlrd.open_workbook("Calculation_file.xls")
> >>> book=xlrd.open_workbook("testbook.xls")
> >>> sh=book.sheet_by_index(0)
> >>> for row in range(sh.nrows):
> 	print sh.row(rx)
> [text:u'name', text:u'address', text:u'ph']
> [text:u'sudhir', text:u'bangalore', number:1234.0]
> [text:u'vinay', text:u'bangalore', number:3264.0]

It helps when asking questions if you copy/paste exactly what is on
your screen;
in this case
    print sh.row(rx)
would have given an error; you must have typed
    for rx in range.....

A row is returned as a sequence of Cell objects. What you are seeing is
Python automatically doing repr(cell) on each cell in the row. The
Cell.__repr__ method formats it that way for debugging. Here are some
examples from a little test file of mine:

>>> import xlrd
>>> bk = xlrd.open_workbook('sjm1.xls')
>>> sh = bk.sheet_by_index(0)
>>> row0 = sh.row(0)
>>> row0
[text:u'fubar', number:1.0, number:2.0]
>>> firstcell = row0[0]
>>> type(firstcell)
<class 'xlrd.sheet.Cell'>
>>> firstcell.ctype
1
>>> # cell type 1 is text
>>> firstcell.value
u'fubar'
>>> repr(firstcell)
"text:u'fubar'"

>
> I am bit confused with slicing. help me....
>
None of the above is anything to do with slicing; is this a 2nd
problem?

Perhaps you are having trouble with this:
>>> help(sh.row_slice)
Help on method row_slice in module xlrd.sheet:

row_slice(self, rowx, start_colx=0, end_colx=None) method of
xlrd.sheet.Sheet instance
    ##
    # Returns a slice of the Cell objects in the given row.
>>>

sh.row_slice(rowx, lo, hi) gives the same result as sh.row(rowx)[lo:hi]
-- it is provided because the latter would be inefficient for getting a
small slice from a long row.

If you are having trouble with the general concept of slicing, perhaps
you might like to try the Python tutorial. Otherwise, please try to be
a bit more specific about what the confusion is.

HTH, and e-mail me if you prefer ...

Cheers,
John




More information about the Python-list mailing list