首页 > 编程语言 > 详细

python应用_读取Excel数据【二】_二次封装之函数式封装

时间:2020-04-18 11:37:32      阅读:48      评论:0      收藏:0      [点我收藏+]

目的:想要把对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) #检测输出结果

python应用_读取Excel数据【二】_二次封装之函数式封装

原文:https://www.cnblogs.com/123anqier-blog/p/12724830.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!