Python根據列名取值讀取Excel單元格的資料
阿新 • • 發佈:2018-12-22
程式碼如下:
class Cellinforeader: """讀取excel的類""" def __init__(self, path=r'C:\Users\Administrator\Desktop\嘉興工參\圈定區域網內鄰區關係(1).xlsx', sheetname='圈定小區'): try: self.workbook = xlrd.open_workbook(path) self.sheet = self.workbook.sheet_by_name(sheetname) except Exception: print(Exception) # 列名與列號字典,例如{'小區名稱':2} self.col_dict = {} self.mismatchedcgi = dict() self.mismatchedcgi_t = dict() self.mismatchedrowid = [] # sheet.ncols: Nominal number of columns in sheet. for i in range(self.sheet.ncols): self.col_dict[self.alltypestrip(self.sheet.cell_value(0, i))] = i # ' abc '.strip()去除字串前後的空格 # 對enbid 'float' object使用strip函式時報錯,所以增加這個函式,使用strip前判斷一下是不是str型別。 @staticmethod def alltypestrip(args): return args.strip() if type(args) is str else args
關鍵程式碼:
self.col_dict = {}
......
......
# sheet.ncols: Nominal number of columns in sheet.
for i in range(self.sheet.ncols):
self.col_dict[self.alltypestrip(self.sheet.cell_value(0, i))] = i
解釋一下,這裡利用dict資料字典的特性,可以動態新增內容成員,利用關鍵字讀取也很方便。
附python官網dict連結: