当前位置:   article > 正文

python读取excel某列数据_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]))    #查看数据类型
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

输出结果为:

['Sheet1']
['', '', '-72.20', '248.84', '-32.67', '156.93', '-49.58', '59.36', '']
248.84
<class 'str'>
  • 1
  • 2
  • 3
  • 4

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

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]))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

结果为:

['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'>
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/209764
推荐阅读
相关标签
  

闽ICP备14008679号