xlrd

John Machin sjmachin at lexicon.net
Tue Aug 5 00:46:40 CEST 2008


On Aug 4, 11:08 pm, Edwin.Mad... at VerizonWireless.com wrote:
> here is working code that will read & display  contents of all rows & columns in all the sheets, you need xlrd 0.6.1
>
> import xlrd, os, sys
>
> book = xlrd.open_workbook(sys.argv[1])
> print "The number of worksheets is", book.nsheets
> for shx in range(book.nsheets):
>    sh = book.sheet_by_index(shx)
>    print 'tab:%s rows:%s cols:%s ' % (sh.name, sh.nrows, sh.ncols)
>    for rx in range(sh.nrows):
>       for cx in range(sh.ncols):
>          try:
>             if sh.row_types(rx)[cx] and sh.row_values(rx)[cx]:

Having "and sh.row_values(rx)[cx]" means that it does not "display
contents of all rows & columns in all the sheets"; it omits cells
which contain 0., "", or FALSE.

Consider getting the row_types and the row_values once per row instead
of once per cell.

>                print '%4s %s' % (xlrd.cellname(rx, cx), sh.row_values(rx)[cx])

If the contents of the cell are a date or an error code, the display
will be rather meaningless.

>          except:
>             print xlrd.cellname(rx, cx), 'Exception - could not read'

I'm having difficulty imagining what could go wrong in your try block,
apart from an IndexError (but you are not addressing cells outside the
arena). If something does go wrong, it would be rather drastic, and
very nice to know exactly what the problem is. As well as printing the
cellname, you should get sys.exc_info()[:2] and print the exception
details. But for unexpected exceptions, I'd prefer to print the "where
am I" info and just re-raise the exception, instead of trying to
continue.

>    print

You can use the supplied script runxlrd.py to get similar information
e.g. on Windows assuming default setup:

prompt>c:\python25\scripts\runxlrd.py show yourfile.xls

For help on displaying dates and error codes, see the get_row_data
function in runxlrd.py, and read the documentation on the Cell class.

Cheers,
John



More information about the Python-list mailing list