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

使用Openpyxl合并多Excel表格数据时输出不符预期的问题

Openpyxl合并多Excel指定列,输出结果不符合预期

我基于Openpyxl写了Python脚本,用来把多个Excel文件的指定列数据合并到新文件里。脚本能正常运行,但输出结果和预期不一样,我已经附上了实际输出与期望输出的截图,完整代码也贴在下面。反复检查代码还是没找到问题,求帮忙排查。

完整代码

# 替换为你的实际完整代码
import openpyxl
import os
from openpyxl import Workbook

# 配置参数
source_dir = "./excel_source"
target_cols = ["A", "C", "E"]
output_file = "merged_output.xlsx"

# 初始化合并工作簿
merged_wb = Workbook()
merged_ws = merged_wb.active
header_added = False

# 遍历目录下的Excel文件
for filename in os.listdir(source_dir):
    if filename.endswith(".xlsx") and not filename.startswith("~$"):
        file_path = os.path.join(source_dir, filename)
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        
        # 添加表头(仅第一次添加)
        if not header_added:
            header = [ws[f"{col}1"].value for col in target_cols]
            merged_ws.append(header)
            header_added = True
        
        # 读取并写入数据行
        for row_idx in range(2, ws.max_row + 1):
            row_data = [ws[f"{col}{row_idx}"].value for col in target_cols]
            merged_ws.append(row_data)

# 保存合并结果
merged_wb.save(output_file)

输出问题详情

  • 实际输出:[结合截图描述,比如「重复添加表头、部分列数据错位、部分文件数据未被提取」]
  • 期望输出:[结合截图描述,比如「仅保留一份表头,所有指定列数据按文件顺序完整合并,无错位」]

实际输出截图:
实际输出

期望输出截图:
期望输出

内容的提问来源于stack exchange,提问作者Jude Jeevan Mahendran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:24:56