一、背景
现有需求,将多个excel的相同sheet页面写入同一个excel。且这些相同excel的sheet页表头和格式相同
所以协助同事编写了核心逻辑实现,方便拓展使用。大家参考的时候灵活组合即可
二、创建实验对象
1、来源excel1:stg.xlsx
sheet页的名称:STG
id | name |
---|---|
1 | a |
2 | b |
3 | c |
2、来源excel2:ods.xlsx
sheet页的名称:ODS
id | name |
---|---|
4 | q |
5 | w |
6 | e |
3、目标excel:target.xlsx
sheet页的名称:STG
id | name |
---|
sheet页的名称:ODS
id | name |
---|
三、程序实现
要求需要合并的excel,相同sheet页的表头一样(否则合并将无任何实际含义)
本程序只实现了合并一个excel的sheet页面,如有特殊需求酌情修改,程序仅供参考
import os
import pandas
TARGET = 'target.xlsx'
STG = 'stg.xlsx'
ODS = 'ods.xlsx'
# 合并excel
def excel_combiner(src_path, target_path, sheet_name):
"""
将来源excel合并到目标excel
:param src_path:
:param target_path:
:param sheet_name:
:return: dataframe合并后的最终excel对象
"""
tar_df_all = None
if not os.path.exists(target_path):
return None
if not os.path.exists(src_path):
return None
tar_data_frame = pandas.DataFrame(pandas.read_excel(target_path, sheet_name=sheet_name, keep_default_na=False))
src_data_frame = pandas.DataFrame(pandas.read_excel(src_path, sheet_name=sheet_name, keep_default_na=False))
if len(tar_data_frame.columns) == 0:
tar_df_all = src_data_frame
tar_df_all = pandas.concat([tar_data_frame, src_data_frame], ignore_index=True)
return tar_df_all
if __name__ == '__main__':
combiner = excel_combiner(STG, TARGET, 'STG')
excel_writer = pandas.ExcelWriter(TARGET)
combiner.to_excel(excel_writer, index=False, sheet_name='STG')
excel_writer.close()