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

如何用OpenPyXL在Python中合并多份带开头空行的Excel文件

使用OpenPyXL合并带前置空行的多个Excel文件

你现在的问题核心是要跟踪目标工作表的当前最后行号,这样后续文件的数据就能从已有内容的下一行开始追加,同时跳过后续文件的表头行。下面是修改后的完整代码,直接就能用:

import openpyxl as xl
from openpyxl import Workbook
import os

def find_xlsx_files():
    dir_path = os.path.dirname(os.path.abspath(__file__))
    res = []
    for file in os.listdir(dir_path):
        if file.endswith('.xlsx'):
            res.append(file)
    return res

# 获取当前目录下所有待合并的xlsx文件
xlsx_files = find_xlsx_files()
if not xlsx_files:
    print("当前目录下没有找到xlsx文件")
    exit()

# 初始化目标工作簿和工作表
target_wb = Workbook()
target_ws = target_wb.active
target_ws.title = "合并结果"

# 记录目标表当前要写入的起始行,初始对应第一个文件的表头行(第3行)
current_target_row = 3

for idx, file_name in enumerate(xlsx_files):
    # 打开当前源文件
    source_wb = xl.load_workbook(file_name)
    source_ws = source_wb.worksheets[0]
    source_max_row = source_ws.max_row
    source_max_col = source_ws.max_column

    # 第一个文件从第3行开始复制(包含表头),后续文件从第4行开始(跳过表头)
    source_start_row = 3 if idx == 0 else 4

    # 逐行复制内容到目标表
    for source_row in range(source_start_row, source_max_row + 1):
        for col in range(2, source_max_col + 1):
            # 读取源单元格值,写入目标单元格
            target_ws.cell(row=current_target_row, column=col).value = source_ws.cell(row=source_row, column=col).value
        # 写完一行,目标行号往后挪一位
        current_target_row += 1

# 保存合并后的文件
target_wb.save('合并结果.xlsx')

关键修改说明

  1. 跟踪写入位置:用current_target_row变量记录每次要写入的起始行,确保后续文件内容追加在已有数据下方,不会覆盖。
  2. 区分表头处理:第一个文件保留表头(从第3行开始复制),后续文件直接从数据行(第4行)开始复制,避免重复表头。
  3. 遍历所有文件:不再只处理第一个文件,自动遍历当前目录下所有xlsx文件。
  4. 简化操作流程:去掉了原代码中先保存目标文件再重新加载的冗余步骤,直接操作新建的工作表即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:33:32