一、安裝xlrd模塊
1、dos命令安裝法:
①到python官網下載http://pypi.python.org/pypi/xlrd模塊安裝,前提是已經安裝了python 環境。
②直接cmd,pip install xlrd即可
2、pycharm中安裝
①:pycharm中File-->settings-->Project:Project Interpreter ,右側“+”點擊,搜索框中搜索xlrd,然后點擊install
二、使用介紹
1:導入
import xlrd
2:打開excel文件讀取數據
data = xlrd.open_workbook(data_file) #data_file為Excel文件路徑
3:常用的函數
1)獲取Excel中一個工作表(2種方法)
table = data.sheet_by_name("Login") #通過名稱獲取 table = data.sheet_by_index(0) #通過索引順序獲取
2)行的操作
nrows = table.nrows #獲取該sheet中有效行數 table.row(rowx) #返回由該行中所有的單元格對象組成的列表 #rowx為數值,獲取第多少行 table.row_slice(rowx) #返回由該行中所有的單元格對象組成的列表,列表中增加text名稱 table.row_values(rowx, start_colx=0, end_colx=None) #返回由該行中所有單元格的數據組成的列表 table.row_types(rowx, start_colx=0, end_colx=None) #返回由該行中所有單元格的數據類型組成的列表 table.row_len(rowx) #返回該列的有效單元格長度
3)列的操作
1 ncols = table.ncols #獲取列表的有效列數 2 table.col(colx, start_rowx=0, end_rowx=None) #返回由該列中所有的單元格對象組成的列表 4 table.col_slice(colx, start_rowx=0, end_rowx=None) #返回由該列中所有的單元格對象組成的列表 6 table.col_types(colx, start_rowx=0, end_rowx=None) #返回由該列中所有單元格的數據類型組成的列表 8 table.col_values(colx, start_rowx=0, end_rowx=None) #返回由該列中所有單元格的數據組成的列表
4:封裝成函數
如圖所示,獲取表格中內容並返回字典形式
import xlrd def get_data(): data_file = r"D:\Workspace-python\Test_interface\Zno_interface\data\data.xlsx" data = xlrd.open_workbook(data_file) table = data.sheet_by_name('score') sheet_name = table.row_values(0) #獲取sheet文件中表頭 for i in range(1,table.nrows): #table.nrows有效行數,根據行數獲取值 lists = dict(zip(sheet_name,table.row_values(i))) #zip和dict為內置函數 print(lists) get_data()
#結果
#{'name': 'zhangsan', 'age': 12.0, 'score': 77.0}
#{'name': 'lisi', 'age': 31.0, 'score': 60.0}