I am working on an excel workbook
. I am using python
script for operating on the workbook
. But there two issues:
1) There are some cells which have integer
values. When I am reading that values and putting the read value into a report file (.txt
), it is appending .0
with the number. Eg. if there is value 6, it is giving 6.0 when it is not supposed to do this. I have read that there is nothing as integer
in excel. Still, I have 1000s of parameters and thus, I cant convert directly all of them to integer
using some python
function because that may convert values which are actually float
also.
2) And when I am reading boolean
TRUE and FALSE, it is giving me 1 and 0. I want to get whatever text
I see in the excel workbook on my desktop. I don't want any conversions like that.
I am using xlrd
for excel
operations in python
.
Please tell me what I should do to solve this problem?
Note: My excel sheet contains more than 100 sheets and I can't modify "true or false" with "1 and 0" etc
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.