合並單元格
操作方法:
1.使用xlrd自帶屬性:merged_cells
# 獲取表格中所有合並單元格位置,以列表形式返回 (起始行,結束行,起始列,結束列)
merged = sheet.merged_cells #結果:[(1,5,0,1),(5,9,0,1)]
2.使用循環判斷是合並單元格還是普通單元格,並將合並單元格中的首行值賦值給合並單元格
def get_cell_type(row_index, col_index): """既能得到合並單元格也能得到普通單元格""" cell_value = None for (rlow, rhigh, clow, chigh) in merged: # 遍歷表格中所有合並單元格位置信息 # print(rlow,rhigh,clow,chigh) if (row_index >= rlow and row_index < rhigh): # 行坐標判斷 if (col_index >= clow and col_index < chigh): # 列坐標判斷 # 如果滿足條件,就把合並單元格第一個位置的值賦給其它合並單元格 cell_value = sheet.cell_value(rlow, clow) print('合並單元格') break # 不符合條件跳出循環,防止覆蓋 else: print('普通單元格') cell_value = sheet.cell_value(row_index, col_index) # else: 添加改行后只那一個單元格的內容5,0 會返回2個值普通單元格/合並單元格 # print('普通單元格') # cell_value = sheet.cell_value(row_index, col_index) return cell_value # 直接輸入單元格的坐標。來獲取單元格內容 # print(get_cell_type(5, 0)) # 利用循環輸出某列的單元格內容 for i in range(1, 9): print(get_cell_type(i, 2))
PS:最簡單的讀取Excel文件中合並單元格操作
問題:
1.當輸出內容時,使用坐標來獲取print,若最外層有else會返回2個值(還在確認若無最外層else是否會有其他問題存在)
2.第一次使用時可以正常,再次使用時sheet.merged_cells返回列表為空??
解決方法:在打開文件中加入formatting_info=True,就能正常顯示