python 将表格转换成字典key:value的形式

转换成key:value的字典形式

def weixinxiaodiao(file_name):
    workbook = openpyxl.load_workbook(f"./excel_file/{file_name}")
    sheet1 = workbook["Sheet1"]
    # list_rows = [[row.value for row in sheet1[i]] for i in range(1, sheet1.max_row + 1)]
    # 获取所有行数据
    list_rows = [[cell.value for cell in row] for row in sheet1.iter_rows()]

    # 提取表头
    headers = list_rows[0]  # 第一行是表头

    # 将每一行数据转换为 key:value 的形式
    data = [dict(zip(headers, row)) for row in list_rows[1:]]
    
    # 打印结果
    print(data)
    return data
## 打印结果[{'下限': '0', '上限': '500', '单价': 100, '最低收费': 100, '原城市': '天津', '目的城市': '天津市'}]

转换成列表形式

def weixinxiaodiao(file_name):
    workbook = openpyxl.load_workbook(f"./excel_file/{file_name}")
    sheet1 = workbook["Sheet1"]
    ist_rows = [[row.value for row in sheet1[i]] for i in range(1, sheet1.max_row + 1)]
    print(ist_rows)
    return ist_rows
## 打印结果 [['下限', '上限', '单价', '最低收费', '原城市', '目的城市'], ['0', '500', 100, 100, '天津', '天津市']]
posted @ 2025-04-29 11:37  darling331  阅读(27)  评论(0)    收藏  举报