You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Openpyxl规整Excel中ProductItems与locations数据格式?

使用Openpyxl规整Excel中ProductItem与Location的关联数据

实现思路

  1. 加载目标Excel文件并定位工作表
  2. 在最左侧插入空列,用于存储对应ProductItem名称
  3. 遍历行数据,通过单元格缩进值区分ProductItem行与Location行:
    • 无缩进的行标记为ProductItem,记录当前ProductItem名称并填充至新列
    • 带缩进的行标记为Location,将当前记录的ProductItem名称填充至新列对应行
  4. 保存规整后的文件

完整代码示例

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 14:40:15