python中如何读取excel某列数据?

发布时间:2022-05-17 09:56:40 人气:2894 作者:多测师

  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 # 获取列数,尽管没用到

python中如何读取excel某列数据?

  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

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

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

  以上内容为大家介绍了python中如何读取excel某列数据?希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线