Python遍历Excel并统计运单数据存入字典的实现问题
需求:统计Excel中承运商对应的运单次数
我需要用Python遍历仅含一列的Excel表格,把承运商名称存入字典,同时统计该名称下方到下一个承运商出现前的日期单元格数量(即运单次数),并将统计值存入字典对应承运商的loads字段。目前已经实现了将承运商名称存入字典,但不知道怎么继续循环统计日期数量并更新字典。
原代码
# Function to add new entries to the dictionary def add_entry(dictionary, key, value): dictionary[key] = value import openpyxl from datetime import datetime # Load the Excel workbook workbook = openpyxl.load_workbook(r'path to carrier2.xlsx') sheet = workbook.active # Assuming you want to work with the active sheet # Dictionary to store data data_dict = {} # Specify the starting row and the number of rows to iterate through start_row = 2 num_rows = sheet.max_row - start_row + 1 # Loop through rows starting from the specified row for i, row in enumerate(sheet.iter_rows(min_row=start_row, max_col=1, max_row=start_row + num_rows - 1), start=start_row): cell_value = row[0].value if cell_value == "Carrier": # Get the value one row above value_above = sheet.cell(row=row[0].row - 1, column=1).value if value_above: add_entry(data_dict, i, {'name': value_above, 'loads': 0}) # Print the dictionary with the saved data print(data_dict) # Close the workbook workbook.close()
Excel表格结构

解决思路
- 遍历过程中维护当前承运商和当前运单计数两个变量,追踪统计状态
- 遇到"Carrier"标识时:
- 若已有正在统计的承运商,先把之前的计数存入字典
- 取出上方的承运商名称,初始化新的计数
- 识别到日期格式的单元格时,直接增加当前计数
- 遍历结束后,处理最后一个承运商的统计数据,避免遗漏
修改后的代码
import openpyxl from datetime import datetime # Load the Excel workbook workbook = openpyxl.load_workbook(r'path to carrier2.xlsx') sheet = workbook.active # 字典存储数据:用承运商名称作为key更直观,也可按需改回原行号 data_dict = {} current_carrier = None current_loads = 0 # 从第2行开始遍历单列数据 for row in sheet.iter_rows(min_row=2, max_col=1, values_only=True): cell_value = row[0] if cell_value == "Carrier": # 先处理上一个承运商的统计结果 if current_carrier is not None: data_dict[current_carrier] = {'name': current_carrier, 'loads': current_loads} # 获取当前承运商名称(当前行的上一行) carrier_name = sheet.cell(row=sheet._current_row - 1, column=1).value current_carrier = carrier_name current_loads = 0 # 重置计数 elif isinstance(cell_value, datetime): # 判断为日期格式,运单计数+1 current_loads += 1 # 处理最后一个承运商的数据 if current_carrier is not None: data_dict[current_carrier] = {'name': current_carrier, 'loads': current_loads} # 打印统计结果 for key, value in data_dict.items(): print(f"承运商: {value['name']}, 运单次数: {value['loads']}") workbook.close()
代码说明
- 移除冗余的
add_entry函数,直接操作字典更简洁 - 使用
values_only=True获取单元格值,提升遍历效率 - 用
isinstance(cell_value, datetime)精准识别日期单元格,避免误统计非日期内容 - 支持处理最后一个承运商的统计数据,不会遗漏收尾数据
- 字典key改用承运商名称,可读性更强;若需保留原行号作为key,可在遇到"Carrier"时记录当前行号替换逻辑
内容的提问来源于stack exchange,提问作者Jerry S
相关产品推荐
相关产品推荐

