xlrd是python用於讀取excel的第三方擴展包,在使用之前需要安裝xlrd庫。
pip show xlrd #檢查是否已經安裝
pip install -U xlrd #安裝xlrd庫
使用介紹:
- 導入模塊
import xlrd from xlrd import open_workbook
- 打開excel表
excel=open_workbook("excel.xls")
- 獲取表格
#通過索引順序獲取
table=excel.sheets()[0] table=excel.sheet_by_index(0) #通過工作表名獲取
table=excel.sheet_by_name(u"Sheet1")
- 獲取行數和列數
#獲取行數
hs = table.nrows #獲取列數
ls = table.ncols
- 獲取一行、一列的值(注意:行號,列號是從索引0開始的)
#打印第一行的值,返回值為列表
rows_values = table.row_values(0) print (rows_values) #打印第一列的值,返回值為列表
cols_values = table.col_values(0) print (cols_values )
- 循環行列表值,獲取所有行和列的值
#獲取行數 hs=table.nrows
#通過行數值的多少遍歷出表格中的值
for i in range(1,hs): print table.row_values(i)
- 應用小實例,將excel表格中的內容保存到一個列表中,並輸出列表內容
#coding=utf-8
import xlrd excel=xlrd.open_workbook(u"test.xlsx") table=excel.sheet_by_index(0) hs=table.nrows data = [] for i in range(0,hs): #print table.row_values
data.append(table.row_values) print (data)