1. 程式人生 > 實用技巧 >python3 openpyxl 操作excel

python3 openpyxl 操作excel


def
checkCorePoint(self): wb = load_workbook(self.targetCoreFile) sheets = wb.sheetnames # 定義一個存放的sheet targetSheet = 'TargetCorePoint' # 判斷是否已經存在這個sheet頁,如果不存在新建一個 if targetSheet not in sheets: cs = wb.create_sheet(targetSheet) else: # 如果已經存在了,那麼刪除舊的,防止資料堆積,重新建立新的sheet頁
cs = wb[targetSheet] wb.remove(cs) cs = wb.create_sheet(targetSheet) sheet = sheets[0] ws = wb[sheet] targetPointList = [] # 遍歷讀取所有行 for row in ws.rows: line = [col.value for col in row] # 講所讀資訊存在list targetPointList.append(line) targetCorePointList
= [['business_ch_name', 'category_id', 'target_id', 'event_type', '是否核心埋點']] # 遍歷埋點list,判斷是否在已知當中 for i in targetPointList: # 如果存在當前資訊增加標識 if i[2] in self.sourceCorePointList: i.append('') # 並把該埋點存放到list targetCorePointList.append(i)
# 遍歷list,並將存放到 TargetCorePoint sheet 頁 for row in targetCorePointList: cs.append(row) wb.save(filename=self.targetCoreFile) print("執行完成!")

參考 :Python - openpyxl 讀寫操作Excel