如何用Python提取Excel中两个已知字段间的可变行数数据
Excel数据提取问题解决
需求说明
需要从Excel文件中提取以下数据:
- Dispatch和Arrival对应的时间
- 第一列中Incident Notes:和Event log(加粗高亮)之间的所有单元格内容,这部分单元格数量不固定:
- 第一个事件:中间有2个单元格内容「Pizza with cheese」、「Did not tip」
- 第二个事件:中间有1个单元格内容「Italian sub」
- 第三个事件:中间有3个单元格内容「Hot wings」、「Rude」、「No street parking」
提取后每个事件的完整数据示例:
- 08/02/2022 4:02:29(Dispatch时间)
- 08/02/2022 4:04:22(Arrival时间)
- Pizza with cheese
- Did not tip
当前代码现状
目前已实现提取Dispatch时间,但无法处理Incident Notes:和Event log之间的可变范围内容:
wb = openpyxl.load_workbook('TestSpreadsheet.xlsx') sheet = wb['Sheet1'] for row in range(1, sheet.max_row): myrow = sheet[row] callstatus = sheet['C' + str(row)].value if callstatus == 'Dispatch:': calltime =sheet['C' + str(row+1)].value print(f" Status: {callstatus} at {calltime}") # TODO: figure out how to pull range of cells between # Incident Notes: and Event log: cells
解决方案
可以通过标记起始行,再用while循环遍历直到终止行的方式,收集中间内容。同时整合Dispatch、Arrival和Incident Notes的信息:
from openpyxl import load_workbook wb = load_workbook('TestSpreadsheet.xlsx') sheet = wb['Sheet1'] max_row = sheet.max_row # 用于存储当前事件的信息 current_event = {} for row_num in range(1, max_row + 1): # 获取当前行A列和C列的值 col_a_value = sheet[f'A{row_num}'].value col_c_value = sheet[f'C{row_num}'].value # 提取Dispatch时间 if col_c_value == 'Dispatch:': current_event['Dispatch'] = sheet[f'C{row_num + 1}'].value # 提取Arrival时间 elif col_c_value == 'Arrival:': current_event['Arrival'] = sheet[f'C{row_num + 1}'].value # 找到Incident Notes的起始行,开始收集中间内容 elif col_a_value == 'Incident Notes:': incident_notes = [] next_row = row_num + 1 # 循环直到碰到Event log while next_row <= max_row: note_value = sheet[f'A{next_row}'].value if note_value == 'Event log': break if note_value is not None: # 跳过空单元格 incident_notes.append(note_value) next_row += 1 current_event['Incident Notes'] = incident_notes # 收集完当前事件所有信息后,打印或存储 print("当前事件数据:") print(f"- Dispatch: {current_event['Dispatch']}") print(f"- Arrival: {current_event['Arrival']}") for note in current_event['Incident Notes']: print(f"- {note}") print("---") # 重置current_event,准备下一个事件 current_event = {}
代码逻辑说明
- 遍历每一行,分别检查A列和C列的内容
- 遇到
Dispatch:或Arrival:时,提取下一行C列的时间存入当前事件字典 - 遇到
Incident Notes:时,从下一行开始用while循环遍历A列,直到碰到Event log,收集中间非空的单元格内容 - 当收集完当前事件的所有信息后,打印输出并重置事件字典,处理下一个事件
内容的提问来源于stack exchange,提问作者Roberto
相关产品推荐
相关产品推荐

