300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 利用openpyxl模块读取excel文件

利用openpyxl模块读取excel文件

时间:2019-01-11 23:03:16

相关推荐

利用openpyxl模块读取excel文件

背景:之前一直想做一个网络设备配置自动化备份的python程序,以前通过读取ini文件的文件实现了,但是ini文件编辑和更新太麻烦,一起想通过读取excel的方式来实现。在老陆的帮忙下,完成了这一个模块。

需求:excel文件中保存了我所有网络设备的信息,包括设备名,品牌,帐号,密码,IP地址,备份命令、连接方式等信息。我想将所有信息读取到一个字典中。key为设备名,value是一个保存具体信息的字典,这个二级字典中又包含了标题和每一行值的对应关系。

思路:

1、用openpyxl读取所有的行到叠代器。

2、第一个for循环完成:将所有行的信息存储到all_line这一个列表中。

3、第二个for循环完成:将所有信息存储到all_dict这一个字典中

4、函数最后return一个包含这个excel表所有信息的字典

实现代码:

from openpyxl import load_workbookimport sysdef get_excel_sections(list_file):wb = load_workbook(list_file) # 载入表格,生成实例,名称叫wbread_table = wb['LIST'] # 读取excel文件中LIST这个表list_all_row = read_table.rows # 读取表中所有的行到叠代器line = [] # 每一行的数据生成为列表,临时变量all_line = [] # 以每一行为单位,存储所有的行的列表all_dict = {} # 总字典for row in list_all_row: # 依次读取每一行for i in range(len(row)): # 读每一行有多少单元格的这么多次line.append(str(row[i].value).strip())all_line.append(line) # 将每一行添加到all_line的列表中line = [] # 重置line列表for i in range(2, len(all_line)): # 从第3行开始读,读到最后一行parameter_dict = dict(zip(all_line[1], all_line[i])) # 形成参数dict字典,二级字典all_dict[all_line[i][0]] = parameter_dict # 第1列的元素作为一级字典的key,二级字典作为value生成总字典wb.close() # 关闭excelreturn all_dict #返回一个字典excel_file = sys.path[0] + '\\list.xlsx'# 指定excel文件路径dict = get_excel_sections(excel_file) # 运行函数print(dict) # 打印结果

运行结果展示:

{'ShenZ-BG2-49F-SW3': {'device_name': 'ShenZ-BG2-49F-SW3', 'area': '储能大厦', 'brand': 'HUAWEI', 'device_ip': '1.1.1.1','device_username': 'luotao', 'device_password': 'xxxxx', 'device_show_config_cmd': 'display current-configuration','ssh_or_telnet': 'ssh', 'device_disable_pager_cmd': 'screen-length 0 temporary','device_quit_cmd': 'None', 'device_prompt': 'None','device_prompt_username': 'None', 'device_prompt_password': 'None'}, 'ShanD-SC2-SW1': {'device_name': 'ShanD-SC2-SW1', 'area': '山东分公司','brand': 'H3C', 'device_ip': '1.1.1.2','device_username': 'luotao','device_password': 'xxxxx', 'device_show_config_cmd': 'display current-configuration', 'ssh_or_telnet': 'ssh', 'device_disable_pager_cmd': 'screen-length disable','device_quit_cmd': 'None','device_prompt': 'None', 'device_prompt_username': 'None', 'device_prompt_password': 'None'}, 'ShanD-BG2-PSW1': {'device_name': 'ShanD-BG2-PSW1','area': '山东分公司', 'brand': 'H3C', 'device_ip': '1.1.1.3', 'device_username': 'luotao', 'device_password': 'xxxxx', 'device_show_config_cmd': 'display current-configuration', 'ssh_or_telnet': 'ssh', 'device_disable_pager_cmd': 'screen-length disable', 'device_quit_cmd': 'None', 'device_prompt': 'None', 'device_prompt_username': 'None','device_prompt_password': 'None'}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。