Python: 使用xlrd读取Excel文件



import xlrd

# 打开文件, 返回一个操作对象
excel_content = xlrd.open_workbook("C:\\Users\\L\\Desktop\\动物.xlsx")

'''检查某个工作表是否导入完毕, 参数为工作表的下表'''
ret_ok = excel_content.sheet_loaded(0)      # True

1-获取所有的工作表目录

names = excel_content.sheet_names()   #  ['动物类别', 'Sheet2', 'Sheet3']

2-获取sheet表, 这里是获取下标为0的工作表

# 方法①
ret1 = excel_content.sheets()[0]

# 方法②
# ret2 = excel_content.sheet_by_index(0)

# 方法③  
# ret3 = excel_content.sheet_by_name("动物类别")

3-获取所有的有效行num(包括中间的空行)

row_num = ret1.nrows    # 16

4-获取某一行的数据

'''返回某一行的数据(list形式), 参数(行数下标)为必填
   如果有合并单元格(例如3个), 把数据归置到左侧第一个, 其余的为空字符串'''
row_data = ret1.row_values(0)    # ['序号', 222.0, '', '', '动物种类', '', ''] 

5-返回该表中最大的有效列数(表横向最宽)

# 方法1
row_cell_num = ret1.row_len(0)  # 6

# 方法2
col_num = ret1.ncols    # 6

6-获取某一列数据, 参数(下标), list返回形式

column_data = ret1.col_values(0) # ['序号', 43528.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0]

7-返回k行(必传)的m-n列(不传m和n就是默认所有的),

   如果包括合并单元格,最左边的单元格有数据, 其它的赋值为空字符串

column_data_mn = ret1.row_values(0)  # k=0, m 和 n 都没传, 默认获取整行数据
# ['序号', 222.0, '', '', '动物种类']


column_data_mn = ret1.row_values(7, start_colx=1, end_colx=3)  # k=0, m=0, n=5  包含m列不包含n列
# [123.0, 321.0]

8-获取指定单元格的内容(行下标, 列下标)

cell_data = ret1.cell(1, 0).value    
# 43528.0  这个单元格是一个日期, 这里的数字代表1990到现在的天数

# 日期转换, 第二个参数是0 (如果你填1 获取的是4年后的日期), 为什么这么设置我也不清楚...'''

cell_data_change = xlrd. xldate_as_datetime(cell_data, 0)   # 2019-03-04 00:00:00

cell_data_change = xlrd. xldate_as_tuple(cell_data, 0)    # (2019, 3, 4, 0, 0, 0)

9-获取指定单元格的格式

cell_type = ret1.cell(1, 0).ctype    # 这里获得是日期格式, 打印出来却是一个3

# 在xlrd中, 数据对应的数据类型:   0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
# 所以这里的3代表的是date类型
发布了73 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_42327755/article/details/88235492