使用 Python 读取 excel 实例

安装包

安装python官方Excel库–>xlrd

操作

准备 excel 表

这里写图片描述

获取一个文件对象
ExcelFile = xlrd.open_workbook(r"/home/python/Desktop/esdemo/demo.xlsx")
获取目标文件的 sheet 名
sheet_list = ExcelFile.sheet_names()
指定读取某个目标 sheet
sheet1_name = ExcelFile.sheet_names()[0]
获取 sheet 内容

如果存在多个 sheet,则我们可以(1)根据sheet索引(2)根据sheet名称 去获取我们指定的 sheet 的内容

sheet = ExcelFile.sheet_by_index(0)
sheet = ExcelFile.sheet_by_name("表1")
获取 sheet 的名称
sheetname = sheet.name
获取 sheet 的行数
rows = sheet.nrows
获取 sheet 的 列数
cols = sheet.ncols
获取整行的值
whole_rows =  sheet.row_values(2) # 获取第3行的内容

['139****1053', 42700.0, '', '百佳', '百佳广场保利丰店', '4403**********7024']
获取整列的值
whole_cols = sheet.col_values(1) # 获取第2列的内容 

['登记时间',
 42699.0,
 42700.0,
 42701.0,
 42701.0,
 42701.0,
 42705.0,
 42705.0,
 42705.0,
 42705.0,
 42705.0]
获取某个单元格的内容
cell_1_0 = sheet.cell(1,0).value
cell_1_0 = sheet.cell_value(1,0)
cell_1_0 =  sheet.row(1)[0].value

'139****5156'
打印单元格的内容格式
In [53]: cell_type_1_0 = cell_1_0.ctype()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-53-f3062d0e27e1> in <module>()
----> 1 cell_type_1_0 = cell_1_0.ctype()

AttributeError: 'str' object has no attribute 'ctype'

In [54]: cell_type_1_0 = sheet.cell(1,0).ctype()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-54-6acfaae3de06> in <module>()
----> 1 cell_type_1_0 = sheet.cell(1,0).ctype()

TypeError: 'int' object is not callable

In [55]: cell_type_1_0 = sheet.cell(1,0).ctype

In [56]: cell_type_1_0
Out[56]: 1

联系方式

QQ:2564493603

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值