1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python+xlrd:实现Excel文件内容读取(全文件or指定sheet页)

Python+xlrd:实现Excel文件内容读取(全文件or指定sheet页)

时间:2019-10-10 04:23:34

相关推荐

Python+xlrd:实现Excel文件内容读取(全文件or指定sheet页)

一、xlrd常用方法简述:

二、封装代码实现如下:

import xlrddef read_excel_data(sheet_page_paramas):"""使用 xlrd 读取 excel 文件内容1、sheet_page_paramas:传入 string 类型的 "all" ,表示读取所有sheet的数据2、sheet_page_paramas:传入 list 类型的 [1,3],表示仅读取第二页和第四页的数据"""# 准备一个空列表,用来存储文件读取的数据data_list = []# .open_workbook():固定方法,读取传入的目录文件xlsx_path = r"./你的excel文件路径.xlsx"# 实例化工作簿对象 bookbook = xlrd.open_workbook(xlsx_path)# .nsheets 方法:获取当前文件的的sheet页数量sheet_num = book.nsheetsprint(f"当前Excel文件,共有 {sheet_num} 页\n")# 传入的sheet页码参数为:all 时,表示需要读取所有sheet页的数据if sheet_page_paramas == "all":for i in range(sheet_num):# 通过页码下标,实例化 对应页码表格 对象sheet = book.sheet_by_index(i)sheet_name = sheet.nameprint(f">>>>>>>>>>>>>>>>>> 正在读取第{i + 1}个sheet,名为《{sheet_name}》的数据 <<<<<<<<<<<<<<<<<<")# 循环遍历 sheet 页的每一行数据for norw in range(1, sheet.nrows):# 读取 excel 指定行的数据value = sheet.row_values(norw)# 将读取的数据,存储于空列表 data_list[] 中data_list.append(value)print(f"当前读取第 {norw} 行的数据,数据内容为:\n{value}\n")# 循环结束后,返回存储测试用例的列表 data_list[]return data_listelif isinstance(sheet_page_paramas, list):for i in list(sheet_page_paramas):if 0 <= i <= sheet_num:# .sheet_by_index(下标):实际页码下标为传入的页面 -1sheet = book.sheet_by_index(i)sheet_name = sheet.nameprint(f">>>>>>>>>>>>>>>>>> 正在读取第{i + 1}个sheet,名为《{sheet_name}》的数据 <<<<<<<<<<<<<<<<<<")# 循环遍历sheet页的每一行数据for norw in range(1, sheet.nrows):value = sheet.row_values(norw)# 将读取的数据,存储于空列表 data_list[] 中data_list.append(value)print(f"当前读取第 {norw} 行的数据,数据内容为:\n{value}\n")else:raise IndexError(f"传入的sheet页码:{i},超过最大页码:{sheet_num}")# 循环结束后,返回存储测试用例的列表 data_list[]return data_listelse:raise TypeError(f"传入的excel_sheetpages数据类型错误,应为list或者指定string参数->all,\n目前入参类型为::{type(sheet_page_paramas)}")if __name__ == '__main__':# print("控制台输出Excel文件全sheet页数据:\n",read_excel_data("all"))print("控制台输出指定页码数据:\n",read_excel_data([1]))""" 以下为代码执行结果:"""/opt/homebrew/bin/python3.9 当前Excel文件,共有 2 页>>>>>>>>>>>>>>>>>> 正在读取第2个sheet,名为《成绩表》的数据 <<<<<<<<<<<<<<<<<<当前读取第 1 行的数据,数据内容为:['语文', '张三', 99.0]当前读取第 2 行的数据,数据内容为:['数学', '李四', 55.0]当前读取第 3 行的数据,数据内容为:['英语', '王五', 70.0]控制台输出指定页码数据:[['语文', '张三', 99.0], ['数学', '李四', 55.0], ['英语', '王五', 70.0]]Process finished with exit code 0

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。