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)
