Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xlrd read number as string

Tags:

python

xlrd

I am trying to read from an xls file a long number (6425871003976) but python keeps trunking it before it reads it as a number not a string (6.42587100398e+12). Is there any method to read it directly as a string even thou in the xls file it is a number?

values = sheet.row_values(rownum)

in values it appears correctly (6425871003976.0) but when I try values[0] it is already switched to the incorrect value.

Solution:

This was my solution using repr():

if type(values[1]) is float:  
    code_str = repr(values[1]).split(".")[0]
else:
    code_str = values[1]
product_code = code_str.strip(' \t\n\r')
like image 590
Virgil Balibanu Avatar asked Aug 20 '15 07:08

Virgil Balibanu


3 Answers

It's the same value. All that's different is how the value is being printed to screen. The scientific notation you get is because to print the number str is called on it. When you print the list of values the internal __str__ method of the list calls repr on each of its elements. Try print(repr(values[0])) instead.

like image 189
Dunes Avatar answered Sep 21 '22 07:09

Dunes


use print "%d" %(values[0])

%d is used for printing integer values

like image 34
Deepak Sharma Avatar answered Sep 20 '22 07:09

Deepak Sharma


This is an example, which bring the value of a cell (in your case it's an int), you need to convert it to a string using the str function

from openpyxl import load_workbook
wb = load_workbook(filename='xls.xlsx', read_only=True)
ws = wb['Sheet1']
for row in ws.rows:
    for cell in row:
        cell_str=str(cell.value)
like image 41
ْزَيْنَب Avatar answered Sep 18 '22 07:09

ْزَيْنَب