python读取包含层级关系的excel
生活随笔
收集整理的這篇文章主要介紹了
python读取包含层级关系的excel
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.場(chǎng)景描述
使用python讀取包含層級(jí)關(guān)系excel,數(shù)據(jù)示例如下圖所示。
2.代碼
import xlrd def read_excel():# 打開文件workbook = xlrd.open_workbook(r'2018年全國(guó)省市區(qū)列表.xlsx')print('所有sheet名稱:', workbook.sheet_names())sheet2 = workbook.sheet_by_index(0) # sheet索引從0開始rows_num = sheet2.nrows # 獲取所有行數(shù)cols_num = sheet2.ncols # 獲取所有列數(shù)province_city_list = []for r in range(1,rows_num):#行索引的取值范圍entity_dict = {}for c in range(cols_num):cell_value = sheet2.row_values(r)[c]# print('第%d行第%d列的值:[%s]' % (r, c, sheet2.row_values(r)[c]))if (cell_value is None or cell_value == ''):cell_value = (get_merged_cells_value(sheet2, r, c))# 設(shè)置各屬性值if c==0:if (cell_value is None or cell_value == ''):entity_dict["province"] = ''else:entity_dict["province"] = cell_valueelif c==1:if (cell_value is None or cell_value == ''):entity_dict["city"] = ''else:entity_dict["city"] = cell_valueelif c==2:if (cell_value is None or cell_value == ''):entity_dict["county"] = ''else:entity_dict["county"] = cell_valueelif c==3:if (cell_value is None or cell_value == ''):entity_dict["station"] = ''else:entity_dict["station"] = cell_valueprint(entity_dict)province_city_list.append(entity_dict)return province_city_list def get_merged_cells(sheet):"""獲取所有的合并單元格,格式如下:[(4, 5, 2, 4), (5, 6, 2, 4), (1, 4, 3, 4)](4, 5, 2, 4) 的含義為:行 從下標(biāo)4開始,到下標(biāo)5(不包含) 列 從下標(biāo)2開始,到下標(biāo)4(不包含),為合并單元格:param sheet::return:"""return sheet.merged_cells def get_merged_cells_value(sheet, row_index, col_index):"""先判斷給定的單元格,是否屬于合并單元格;如果是合并單元格,就返回合并單元格的內(nèi)容:return:"""merged = get_merged_cells(sheet)for (rlow, rhigh, clow, chigh) in merged:if (row_index >= rlow and row_index < rhigh):if (col_index >= clow and col_index < chigh):cell_value = sheet.cell_value(rlow, clow)# print('該單元格[%d,%d]屬于合并單元格,值為[%s]' % (row_index, col_index, cell_value))return cell_valuebreakreturn None if __name__ == "__main__":province_city_list = read_excel()for line in province_city_list:print(line)打印輸出:
{'province': '北京市', 'city': '北京市', 'county': '東城區(qū)', 'station': '景山街道'}
{'province': '北京市', 'city': '北京市', 'county': '西城區(qū)', 'station': '金融街街道'}
{'province': '北京市', 'city': '北京市', 'county': '朝陽(yáng)區(qū)', 'station': '朝外街道'}
...
轉(zhuǎn)載于:https://www.cnblogs.com/cupleo/p/13815125.html
總結(jié)
以上是生活随笔為你收集整理的python读取包含层级关系的excel的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机设备2后符号,表情符号含义展示的方
- 下一篇: tabar被手机虚拟键挡住_bug_ _