Python3功能篇六:如何读取Excel里的数据?

记录一下,方便以后翻阅~
开发环境:PyCharm2019.2.3 社区版
Python版本:3.8

主要代码如下:

# -*- coding: utf-8 -*-
# 作者:闲人Ne
# 格言:学到就要教人,赚到就要给人
# 描述:获取Excel数据
# 日期: 2020年12月09日
import xlrd


def read_excel(file_path):
    target_excel = xlrd.open_workbook(file_path)            # 打开目标文件
    all_sheet_names = target_excel.sheet_names()            # 获取所有sheet的名字(list类型)
    print('Excel所有sheet表的名字分别是:', all_sheet_names)
    sheet1_name = target_excel.sheet_names()[0]             # 获取sheet1的名字
    print('sheet1的名字是:', sheet1_name)
    sheet1_content1 = target_excel.sheet_by_index(0)        # sheet1从索引0开始
#   sheet1_content2 = target_excel.sheet_by_name('Sheet1')  # 另一种方法是按sheet名字获取sheet内容(不推荐,因为要输入正确的名字)
    print('sheet1的名字、行数、列数分别为:', sheet1_content1.name, sheet1_content1.nrows, sheet1_content1.ncols)  # 名称,行数,列数
    rows = sheet1_content1.row_values(3)                    # sheet1第四行所有数据
    cols = sheet1_content1.col_values(2)                    # sheet1第三列所有数据
    print('第3行的数据分别为:', rows)
    print('第2列的数据分别为:', cols)
    print(sheet1_content1.cell(1, 0).value)                 # 获取单元格[第1行第0列]的内容
    print(sheet1_content1.cell_value(2, 2))                 # 获取单元格[第2行第2列]的内容
    print(sheet1_content1.row(3)[3].value)                  # 获取单元格[第3行第3列]的内容
    # Tips: python读取excel中单元格的内容返回的有5种类型 [0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error]
    print(sheet1_content1.cell(1, 0).ctype)                 # 获取单元格内容的数据类型
    
if __name__ == '__main__':
FilePath = 'F:\\5_PyCharm_Python3.8_Workplaces\\ReadExcelInfo\\1234.xlsx'
read_excel(FilePath)

# —————— Copyright (C)2020 闲人Ne. All Rights Reserved —————— END OF FILE —————— #

运行结果如下:
先看下Excel里的数据
在这里插入图片描述
在看下Python运行结果:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天亮继续睡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值