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

Python合并多Excel文件列错位:后续数据行下移问题求助

修复Python合并Excel时后续文件数据行错位问题

问题根源

  1. 行索引持续累加:原代码中row_index在遍历所有文件的行时不断自增,第一个文件写完28行后row_index变为29,导致后续文件从第29行开始写入,无法对齐前28行。
  2. 列位置映射错误:原代码用j+start_col计算列字母,会把每个文件的列都从D列开始重新排列,而非对应原文件的实际列位置,导致数据写入错误列。
  3. 列索引丢失:读取文件时未保留原Excel的列索引,无法准确匹配模板中的目标列。

修正后的代码

from openpyxl.utils import get_column_letter
import pandas as pd

def import_files():
    template_sheet2 = template_wb["TT Matrix"]
    
    for excelfile in excelfiles:
        # 读取整个工作表,保留原列索引(header=None时列名是0开始的索引)
        full_df = pd.read_excel(excelfile, sheet_name="TT Matrix", header=None)
        # 过滤列:排除前3列(0,1,2)和最后4列
        total_cols = full_df.shape[1]
        keep_cols = [col for col in range(total_cols) if col not in range(3) and col not in range(total_cols-4, total_cols)]
        df = full_df[keep_cols]
        
        # 只保留有非空值的列,且仅取前28行数据
        df = df.loc[:, df.notna().any()].head(28)
        
        # 遍历每一列,按原Excel列索引匹配模板列
        for original_col_idx in df.columns:
            # 原Excel列索引(0开始)转openpyxl列号(1开始),再转列字母
            col_letter = get_column_letter(original_col_idx + 1)
            # 遍历前28行,写入模板对应位置
            for row_num, value in enumerate(df[original_col_idx], start=1):
                if pd.notna(value):
                    template_sheet2[f"{col_letter}{row_num}"].value = value

    # 若需要从文件同步列头,可取消以下注释(假设列头在第一行)
    # for excelfile in excelfiles:
    #     header_row = pd.read_excel(excelfile, sheet_name="TT Matrix", nrows=1, header=None)
    #     for col_idx in keep_cols:
    #         col_letter = get_column_letter(col_idx + 1)
    #         header_value = header_row.iloc[0, col_idx]
    #         if pd.notna(header_value):
    #             template_sheet2[f"{col_letter}1"].value = header_value

关键修改说明

  • 保留原列索引:先读取完整工作表再过滤列,确保df.columns对应原Excel的列索引,精准匹配模板列位置。
  • 固定行范围:每个文件仅处理前28行,行号从1到28循环,不再跨文件累加行索引。
  • 精准列映射:直接用原列索引计算Excel列字母,避免列位置错乱。
  • 空值判断:仅写入非空值,防止覆盖模板中已有数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:17:18