成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

如何在Python對Excel進行讀取

瀏覽:134日期:2022-07-22 17:52:46

在python自動化中,經(jīng)常會遇到對數(shù)據(jù)文件的操作,比如添加多名員工,但是直接將員工數(shù)據(jù)寫在python文件中,不但工作量大,要是以后再次遇到類似批量數(shù)據(jù)操作還會寫在python文件中嗎?

應(yīng)對這一問題,可以將數(shù)據(jù)寫excel文件,針對excel 文件進行操作,完美解決。

本文僅介紹python對excel的操作

安裝xlrd 庫

xlrd庫 官方地址:https://pypi.org/project/xlrd/

pip install xlrd

如何在Python對Excel進行讀取

筆者在安裝時使用了 pip3 install xlrd

原因:筆者同時安裝了python2 和 python3

如果pip的話會默認(rèn)將庫安裝到python2中,python3中不能直接調(diào)用。

那么到底是使用pip 還是pip3進行安裝呢?

如果系統(tǒng)中只安裝了Python2,那么就只能使用pip。

如果系統(tǒng)中只安裝了Python3,那么既可以使用pip也可以使用pip3,二者是等價的。

如果系統(tǒng)中同時安裝了Python2和Python3,則pip默認(rèn)給Python2用,pip3指定給Python3用。

Xlrd 庫簡單的使用

以如下excel文件為例進行操作

文件名為demo,有兩個sheet,名為工作表1和工作表2

工作表1中有如下數(shù)據(jù)

如何在Python對Excel進行讀取

簡單的使用

# coding=utf-8import xlrd# 打開文件data = xlrd.open_workbook(’file/demo.xlsx’)# 查看工作表data.sheet_names()print('sheets:' + str(data.sheet_names()))# 通過文件名獲得工作表,獲取工作表1table = data.sheet_by_name(’工作表1’)# 打印data.sheet_names()可發(fā)現(xiàn),返回的值為一個列表,通過對列表索引操作獲得工作表1# table = data.sheet_by_index(0)# 獲取行數(shù)和列數(shù)# 行數(shù):table.nrows# 列數(shù):table.ncolsprint('總行數(shù):' + str(table.nrows))print('總列數(shù):' + str(table.ncols))# 獲取整行的值 和整列的值,返回的結(jié)果為數(shù)組# 整行值:table.row_values(start,end)# 整列值:table.col_values(start,end)# 參數(shù) start 為從第幾個開始打印,# end為打印到那個位置結(jié)束,默認(rèn)為noneprint('整行值:' + str(table.row_values(0)))print('整列值:' + str(table.col_values(1)))# 獲取某個單元格的值,例如獲取B3單元格值cel_B3 = table.cell(3,2).valueprint('第三行第二列的值:' + cel_B3)

運行后結(jié)果

如何在Python對Excel進行讀取

項目中使用

獲得所有的數(shù)據(jù)

# coding=utf-8import xlrddef read_xlrd(excelFile): data = xlrd.open_workbook(excelFile) table = data.sheet_by_index(0) for rowNum in range(table.nrows): rowVale = table.row_values(rowNum) for colNum in range(table.ncols): if rowNum > 0 and colNum == 0: print(int(rowVale[0])) else: print(rowVale[colNum]) print('---------------') # if判斷是將 id 進行格式化 # print('未格式化Id的數(shù)據(jù):') # print(table.cell(1, 0)) # 結(jié)果:number:1001.0if __name__ == ’__main__’: excelFile = ’file/demo.xlsx’ read_xlrd(excelFile=excelFile)

結(jié)果

如何在Python對Excel進行讀取

如果在項目中使用則可將內(nèi)容方法稍為做修改,獲得所有的數(shù)據(jù)后,將每一行數(shù)據(jù)作為數(shù)組進行返回

# coding=utf-8import xlrddef read_xlrd(excelFile): data = xlrd.open_workbook(excelFile) table = data.sheet_by_index(0) dataFile = [] for rowNum in range(table.nrows): # if 去掉表頭 if rowNum > 0: dataFile.append(table.row_values(rowNum)) return dataFileif __name__ == ’__main__’: excelFile = ’file/demo.xlsx’ print(read_xlrd(excelFile=excelFile))

結(jié)果

如何在Python對Excel進行讀取

以上就是如何在Python對Excel進行讀取的詳細(xì)內(nèi)容,更多關(guān)于python對Excel讀取的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: python
相關(guān)文章: