Python:使用xlrd从Excel读取百分比值

问题描述

我正在尝试使用xlrd从excel读取百分比值。但输出保持为1.0。有没有一种方法可以按百分比加载它而不更改值?

以下是我的Excel工作表中的内容

enter image description here

代码

for r in range(1,xlsheet.nrows):
    num_cols = xlsheet.ncols
    print('-'*40)
    print('Row: %s' % r)
    for col_idx in range(1,num_cols):​for r in range(1,num_cols):
        cell_obj = xlsheet.cell(r,col_idx)
        print('Column:[%s] cell_obj: [%s]' % (col_idx,cell_obj))

我得到的输出

Row: 2
Column:[1] cell_obj: [number:1.0]
Column:[2] cell_obj: [number:1.0]
Column:[3] cell_obj: [number:1.0]
Column:[4] cell_obj: [number:1.0]
Column:[5] cell_obj: [number:1.0]
Column:[6] cell_obj: [number:1.0]
Column:[7] cell_obj: [number:1.0]
Column:[8] cell_obj: [number:1.0]
Column:[9] cell_obj: [number:1.0]
Column:[10] cell_obj: [number:1.0]
Column:[11] cell_obj: [number:1.0]
Column:[12] cell_obj: [number:1.0]

解决方法

您可以使用熊猫将整个excel转换为数据框,例如:

excel_dataframe = pd.read_excel(excel_file,sheet_name=s)

,然后使用Apply Map转换为字符串。

 excel_dataframe = excel_dataframe.applymap(str)

这会将excel中的所有单元格转换为字符串,这样您将获得一个字符串对象和正确的值