1、编写要读取的excel
2、DOS命令中安装xlrd:pip install xlrd
在线安装下载地址:https://pypi.org/project/pip/
如果是独立项目需要在pycharm中再次安装,选择系统项目不需要再安装
3、查看操作手册:百度、博客园
4、把excel放到项目文件夹中
5、创建基础学生信息类,并写一个构造方法
class TestCaseBaseInfo:
def __init__(self,case_id,case_name,module):
self.case_id = case_id
self.case_name = case_name
self.module = module
def show(self):
pass
6、新建一个stu_utils模块,并导入将要用到的包
import os
import xlrd
from exce_read.student_base_info import StudentBaseInfo(这个是excel的类)
7、得到当前编码模块的所在文件的地址
current_path = os.path.dirname(__file__)
8、得到excel地址,下面两种方法都可以
# excel_path = os.path.join(current_path,'../date/stu_info.xlsx')
excel_path = current_path+'/../date/stu_info.xlsx'
9、使用xlrd的open打开excel
workbook=xlrd.open_workbook(excel_path)
10、得到想要的tab
sheet = workbook.sheet_by_index(0)
sheet = workbook.sheet_by_name('Sheet1')
12、定义一个空列表用了存储4个对象
studens_info = []
13、实例化一个对象存放一行的数据
student = StudentBaseInfo(sheet.cell_value(1,0),sheet.cell_value(1,1),
sheet.cell_value(1,2),int(sheet.cell_value(1,3)),
int(sheet.cell_value(1,4)))
14、使用for循环得到4个对象并且追加到定义好的studens_info中
studens_info = []
for i in range(1,sheet.max_cols):
student = StudentBaseInfo(sheet.cell_value(i,0),sheet.cell_value(i,1),
sheet.cell_value(i,2),int(sheet.cell_value(i,3)),
int(sheet.cell_value(i,4)))
studens_info.append(student)
15、打印列表中对象的值
print(studens_info[3].stu_age)
16、封装成为一个公共的方法
def red_excel_get_studentinfo(file_path):
workbook=xlrd.open_workbook(file_path)
sheet = workbook.sheet_by_name('Sheet1')
studens_info = []
#一行就是一个对象
for i in range(1,sheet.nrows):
student = StudentBaseInfo(sheet.cell_value(i,0),sheet.cell_value(i,1),
sheet.cell_value(i,2),int(sheet.cell_value(i,3)),
int(sheet.cell_value(i,4)))
studens_info.append(student)
return studens_info
17、在当前模块测试
if __name__ == '__main__':
red_excel = red_excel_get_studentinfo(excel_path)
print(red_excel[3].stu_age)
18、在其他模块调用
import os
from exce_read.excel_utils import read_excel_get_studentinfo
current_path = os.path.dirname(__file__)
#2、得到Excel的路径
excel_path = current_path +'/../date/stu_info.xlsx'
#调用excel_utils模块中read_excel_get_studentinfo函数并传入Excel的路径
stus =read_excel_get_studentinfo(excel_path)
print(stus[2].stu_name)