使用 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

猜你喜欢

转载自blog.csdn.net/Enjolras_fuu/article/details/82112311