利用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_workbook
import sys

def get_excel_sections(list_file):
    wb = load_workbook(list_file)  # 载入表格,生成实例,名称叫wb
    read_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()    # 关闭excel
    return 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'}
}

猜你喜欢

转载自blog.csdn.net/netlt/article/details/121371342