The Python Oracle

Not able to read data from excel as it is seen on desktop

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping

--

Chapters
00:00 Not Able To Read Data From Excel As It Is Seen On Desktop
01:06 Answer 1 Score 3
01:22 Accepted Answer Score 2
02:31 Thank you

--

Full question
https://stackoverflow.com/questions/2224...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27 #xlrd

#avk47



ANSWER 1

Score 3


for the boolean question you can test ctype:

for rx in range(ws.nrows):
        for cx in range(ws.ncols):
            print ws.cell(rx,cx).value, ws.cell(rx,cx).ctype

if the excel original cell is "TRUE" FALSE" the ctype value is 4




ACCEPTED ANSWER

Score 2


xlrd is giving you all your numbers as floats, and your booleans as integers. How you print them out is purely a python matter.

I'll asume you already know which cells contain boolean values. (If you don't, check the cell's ctype as shown in the answer by Massimo Fuccillo-- see @JohnY's comment below for details.) You can print boolean cells as True and False by simply printing bool(var) instead of var:

>>> var = 1
>>> print bool(var)
True

When writing to a file this will be output as the string 'True' (resp. 'False'), as intended.

Since Excel does not distinguish between ints and floats, we'll assume that by integer you mean any number whose fractional part is zero. When python prints a float it adds .0 to preserve the information that it is a float.

The simplest solution would be to suppress this if you format your numbers for output with "%g":

>>> "%g" % 6.0
'6'

However, "%g" will round real numbers to six significant digits by default (though you can specify a different precision).

>>> "%g" % 2500.03
'2500.03'
>>> "%g" % 2500.003
'2500'

So it's safer if you detect integral values yourself, and print them out accordingly:

if int(var) == var:
    print int(var)
else:
    print var

I recommend doing it this way.