python读取excel某列数据

文章目录

  • 一、python读取excel某列数据
  • 二、将读取的数据变为浮点数


一、python读取excel某列数据

import xlrd

worksheet = xlrd.open_workbook('E:\\Crawl\\000002.xls')
sheet_names= worksheet.sheet_names()
print(sheet_names)
for sheet_name in sheet_names:
    sheet = worksheet.sheet_by_name(sheet_name)
    rows = sheet.nrows # 获取行数
    cols = sheet.ncols # 获取列数,尽管没用到
    all_content = []


    cols = sheet.col_values(3) # 获取第二列内容, 数据格式为此数据的原有格式(原:字符串,读取:字符串;  原:浮点数, 读取:浮点数)
    print(cols)
    print(cols[3])
    print(type(cols[3]))    #查看数据类型

输出结果为:

['Sheet1']
['', '', '-72.20', '248.84', '-32.67', '156.93', '-49.58', '59.36', '']
248.84
<class 'str'>

二、将读取的数据变为浮点数

import xlrd

worksheet = xlrd.open_workbook('E:\\Crawl\\000002.xls')
sheet_names= worksheet.sheet_names()
print(sheet_names)
for sheet_name in sheet_names:
    sheet = worksheet.sheet_by_name(sheet_name)
    rows = sheet.nrows # 获取行数
    cols = sheet.ncols # 获取列数,尽管没用到
    all_content = []

    for i in range(rows) :
        cell = sheet.cell_value(i, 3) # 取第二列数据
        try:
            cell = float(cell) # 转换为浮点数
            all_content.append(cell)
        except ValueError:
            pass
    print(all_content)
    print(all_content[3])
    print(type(all_content[3]))

结果为:

['Sheet1']
[-72.2, 248.84, -32.67, 156.93, -33.53, 64.06, -47.0, 117.33, -31.6, 62.56, -33.79, 30.63, -59.65, 53.36, -57.73, 34.15, -60.0, 161.36, -60.0, 41.3, -50.77, 375.31, -43.66, 167.79, -57.47, 62.4, -53.31, 98.65, -37.41, 68.59, -42.04, 54.28, -58.9, 64.21, -51.92, 36.0, -49.02, 630.77, -35.75, 160.82, -51.98, 31.93, -80.17, 198.75, -35.77, 34.31, -46.24, 84.36, -46.82, 321.93, -33.41, 120.85, -49.58, 59.36]
156.93
<class 'float'>

你可能感兴趣的:(python)