如何在Python對Excel進行讀取

在python自動化中,常常會遇到對數據文件的操做,好比添加多名員工,可是直接將員工數據寫在python文件中,不但工做量大,要是之後再次遇到相似批量數據操做還會寫在python文件中嗎?python

  應對這一問題,能夠將數據寫excel文件,針對excel 文件進行操做,完美解決。數組

  本文僅介紹python對excel的操做app

安裝xlrd 庫ide

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

  pip install xlrd3d


v2-c2d12920fe50c612eea6927810fd26c9_720w.png


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

  緣由:筆者同時安裝了python2 和 python3blog

  若是pip的話會默認將庫安裝到python2中,python3中不能直接調用。索引

  那麼究竟是使用pip 仍是pip3進行安裝呢?ip

    若是系統中只安裝了Python2,那麼就只能使用pip。

    若是系統中只安裝了Python3,那麼既可使用pip也可使用pip3,兩者是等價的。

    若是系統中同時安裝了Python2和Python3,則pip默認給Python2用,pip3指定給Python3用。

Xlrd 庫簡單的使用

  以以下excel文件爲例進行操做

  文件名爲demo,有兩個sheet,名爲工做表1和工做表2

  工做表1中有以下數據


v2-02559d4f7fb869abd4f430604210e5de_720w.png


簡單的使用

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

運行後結果


v2-4710c4497314dc338fbc58e00ca8dd3f_720w.png


項目中使用

  得到全部的數據

# coding=utf-8
 
import xlrd
 
def 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的數據:")
 # print(table.cell(1, 0))
 # 結果:number:1001.0
 
 
if __name__ == '__main__':
 excelFile = 'file/demo.xlsx'
 read_xlrd(excelFile=excelFile)

結果


v2-1f050740de053766155915b1bbf0b01c_720w.png


若是在項目中使用則可將內容方法稍爲作修改,得到全部的數據後,將每一行數據做爲數組進行返回

# coding=utf-8
 
import xlrd
 
def 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 dataFile
 
 
if __name__ == '__main__':
 excelFile = 'file/demo.xlsx'
 print(read_xlrd(excelFile=excelFile))

結果


v2-fd4ab86424c8615aa66014910f4368a3_720w.png

相關文章
相關標籤/搜索