111

import pandas as pd

# ========== 参数配置 ==========
file_path = "data.xlsx"        # Excel 文件路径
sheet1 = "Sheet_A"
sheet2 = "Sheet_B"
output_sheet = "Merged_Sheet"
output_file = "merged_result.xlsx"

# ========== 读取数据 ==========
df1 = pd.read_excel(file_path, sheet_name=sheet1)
df2 = pd.read_excel(file_path, sheet_name=sheet2)

# ========== 选择列更多的 Sheet 作为主表 ==========
if df1.shape[1] >= df2.shape[1]:
    base_df = df1.copy()
    other_df = df2.copy()
else:
    base_df = df2.copy()
    other_df = df1.copy()

base_columns = base_df.columns.tolist()

# ========== 对齐列 ==========
aligned_data = []

for col in base_columns:
    if col in other_df.columns:
        aligned_data.append(other_df[col])
    else:
        # 不存在的列补空
        aligned_data.append(pd.Series([None] * len(other_df), name=col))

aligned_df = pd.concat(aligned_data, axis=1)

# ========== 合并数据 ==========
final_df = pd.concat([base_df, aligned_df], ignore_index=True)

# ========== 保存结果 ==========
with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
    final_df.to_excel(writer, sheet_name=output_sheet, index=False)

print("✅ 合并完成,已保存为:", output_file)

 

posted @ 2026-05-17 11:20  红莲の狮子  阅读(7)  评论(0)    收藏  举报