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

求Python代码实现Excel1格式转换为Excel2格式

解决方案:将分组式Excel转换为扁平结构

从截图可知,Excel1为分组层级结构(主项如Item A/B/C作为标题,下方对应子项与数值),Excel2为扁平行结构(每个子项单独成行,关联对应主项)。核心逻辑是遍历行时记录当前活跃主项,遇到子项则将主项、子项、数值组合为新行。

依赖安装

首先确保安装所需库:

pip install pandas openpyxl

转换代码

import pandas as pd

# 读取源Excel文件(替换为你的源文件路径和工作表名)
df = pd.read_excel("excel1.xlsx", sheet_name="Sheet1", header=None)

result_data = []
current_main_item = None

# 遍历每一行处理数据
for _, row in df.iterrows():
    col1_val = row[0]
    col2_val = row[1]
    
    # 识别主项:第一列非空、第二列为空
    if pd.notna(col1_val) and pd.isna(col2_val):
        current_main_item = col1_val
    # 识别子项:两列均非空,组合数据
    elif pd.notna(col1_val) and pd.notna(col2_val):
        result_data.append({
            "Main Item": current_main_item,
            "Sub Item": col1_val,
            "Value": col2_val
        })

# 转换为DataFrame并保存
result_df = pd.DataFrame(result_data)
result_df.to_excel("excel2.xlsx", index=False)

关键说明

  • header=None:因为源Excel没有表头,直接按列索引读取
  • 主项/子项判断:完全匹配截图里的格式特征——主项仅第一列有内容,子项两列均有内容
  • 结果保存:index=False避免生成多余的索引列,输出结构与Excel2完全一致

调整建议

如果源文件的主项有特殊格式(比如加粗、合并单元格),可以改用openpyxl直接读取单元格样式来判断主项,示例片段:

from openpyxl import load_workbook

wb = load_workbook("excel1.xlsx")
ws = wb["Sheet1"]

for row in ws.iter_rows(values_only=False):
    cell1 = row[0]
    cell2 = row[1]
    # 通过字体加粗判断主项
    if cell1.value and not cell2.value and cell1.font.bold:
        current_main_item = cell1.value
    elif cell1.value and cell2.value:
        result_data.append({
            "Main Item": current_main_item,
            "Sub Item": cell1.value,
            "Value": cell2.value
        })

内容的提问来源于stack exchange,提问作者Suraj Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:57:17