
示例數(shù)據(jù)
#安裝包
pip install xlrd
#調(diào)用包
import xlrd
#打開一個excel并創(chuàng)建對象存儲
data=xlrd.open_workbook("test.xlsx")
#獲取文件中所有sheet的名稱
data.sheet_names()
#根據(jù)工作表的名稱獲取工作表的內(nèi)容
text=data.sheet_by_name("sheet1")
#根據(jù)工作表的名稱獲取工作表的行數(shù)、列數(shù)及其名稱
name=table.names
rownumber=table.nrows
colnuber=table.ncols
#獲取單元格內(nèi)容的三種方式
table.cell(i,j).value
table.cell_value(i,j)
table.row(i)[j].value
#獲取單元格的數(shù)據(jù)類型
table.cell(i,j).ctype
type(table.cell_value(i,j))
#xlrd的數(shù)據(jù)類型:0 empty,1 string,2 number,3 date,4 boolean,5 error
#默認(rèn)excel直接取出的數(shù)據(jù)直接打印會有問題:數(shù)字一律按照浮點(diǎn)型打印,日期輸出成一串小數(shù),布爾值輸出0或者1,所以我們必須在程序中做判斷處理轉(zhuǎn)換成我們需要的數(shù)據(jù)類型
#獲取工作表第一行所有內(nèi)容
table.row_values(0)
#獲取工作表的第一列所有內(nèi)容
table.col_values(0)
Excel中的日期轉(zhuǎn)換
此時需要調(diào)用xlrd的xldate_as_tuple模塊或者xldate_as_datetime模塊
from xlrd import xldate_as_tuple
from xlrd import xldate_as_datetime
import date
xlrd.xldate_as_tuple(table.cell_value(2,2),0)
xldate_as_tuble(date,mode),此函數(shù)有兩個參數(shù),第一個參數(shù)是excel的小數(shù)日期,xldate_as_tuple第二個參數(shù)有兩種取值,0或者1,0是以1900-01-01為基準(zhǔn)的日期,而1是1904-01-01為基準(zhǔn)的日期。該函數(shù)返回的是一個元組,他的值類似:(year, month, day, hour, minute, nearest_second)
print(sheet1.row(1))
[number:1.0, text:'張三', xldate:32874.0]
print(xlrd.xldate_as_tuple(sheet1.cell_value(1,2),0))##直接轉(zhuǎn)換成元祖的形式
(1990, 1, 1, 0, 0, 0)
##直接轉(zhuǎn)換成datetime的形式
xlrd.xldate.xldate_as_datetime(sheet1.cell(1,2).value, 0)
datetime.datetime(1990, 1, 1, 0, 0)