简体   繁体   中英

xlrd read number as string

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')

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.

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)

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

%d is used for printing integer values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM