python应用_读取Excel数据【二】_二次封装之函数式封装
目的:想要把对Excel文件读取做成一个通用的函数式封装,便于后续简单调用,隔离复杂性。
未二次封装前原代码:
#coding=gbk
import os
import xlrd
current_path=os.path.dirname(__file__)
excel_path=os.path.join(current_path,'../testcase.xlsx')
workbook=xlrd.open_workbook(excel_path)
sheet=workbook.sheet_by_index(0)
all_case_info = []
for i in range(1,sheet.nrows):
case_info = []
for j in range(0,sheet.ncols):
case_info.append(sheet.cell_value(i,j))
all_case_info.append(case_info)
print(all_case_info)
更改后:
原文件:
#coding=gbk
import os
import xlrd
current_path=os.path.dirname(__file__)
excel_path=os.path.join(current_path,'../testcase.xlsx')
def read_excel_date_convert_case_info(excel_path):
workbook = xlrd.open_workbook(excel_path)
sheet = workbook.sheet_by_index(0)
all_case_info = []
for i in range(1,sheet.nrows):
case_info = []
for j in range(0,sheet.ncols):
case_info.append(sheet.cell_value(i,j))
all_case_info.append(case_info)
return all_case_info #一定要有返回
#顶层代码调试
if __name__ == '__main__':
current_path = os.path.dirname(__file__)
excel_path = os.path.join(current_path, '../testcase.xlsx')
cases=read_excel_date_convert_case_info(excel_path)
print(cases)
调用:
#coding=gbk
import os
from test0418.demo02 import read_excel_date_convert_case_info #引入对应的函数
current_path = os.path.dirname(__file__)
excel_path = os.path.join(current_path, '../testcase.xlsx')
cases = read_excel_date_convert_case_info(excel_path) #别人调用时候只需要import该函数,然后直接
print(cases) #检测输出结果