如何用Python Openpyxl规整Excel中ProductItems与locations数据格式?
使用Openpyxl规整Excel中ProductItem与Location的关联数据
实现思路
- 加载目标Excel文件并定位工作表
- 在最左侧插入空列,用于存储对应ProductItem名称
- 遍历行数据,通过单元格缩进值区分ProductItem行与Location行:
- 无缩进的行标记为ProductItem,记录当前ProductItem名称并填充至新列
- 带缩进的行标记为Location,将当前记录的ProductItem名称填充至新列对应行
- 保存规整后的文件
完整代码示例
from openpyxl import load_workbook # 替换为你的Excel文件路径 source_file = "your_source_file.xlsx" # 加载可编辑的工作簿 wb = load_workbook(source_file) ws = wb.active # 操作默认工作表,指定表名可改为wb["你的工作表名"] # 在最左侧插入空列(A列) ws.insert_cols(1) # 设置新列标题(按需调整) ws["A1"] = "ProductItem" current_product = None # 从第二行开始遍历(假设第一行是表头) for row_num in range(2, ws.max_row + 1): target_cell = ws.cell(row=row_num, column=2) # 原数据列现在是B列 cell_value = target_cell.value if not cell_value: continue # 通过缩进判断是否为Location行(缩进值>0即为Location) indent = target_cell.alignment.indent if target_cell.alignment else 0 if indent == 0: # 记录当前ProductItem并填充到A列 current_product = cell_value ws.cell(row=row_num, column=1).value = current_product else: # 填充关联的ProductItem到A列 if current_product: ws.cell(row=row_num, column=1).value = current_product # 保存为新文件,避免覆盖原数据 wb.save("formatted_product_data.xlsx")
关键细节说明
- 缩进判断逻辑:依赖
openpyxl读取单元格的alignment.indent属性,若你的文件中Location行的缩进判断不生效,可替换为其他特征(比如ProductItem行字体加粗、内容前缀特征等) - 行范围调整:如果原文件无表头,可将遍历起始行改为
range(1, ws.max_row + 1) - 文件保存:建议保存为新文件,防止误操作覆盖原始数据
内容的提问来源于stack exchange,提问作者Volkan
相关产品推荐
相关产品推荐

