如何将多份DataFrame写入Excel不同工作表且避免数据覆盖?
解决方案:实现多程序写入同一Excel的独立工作表
核心问题在于你的所有程序都在写入同一个工作表名(JAron),且未正确利用追加模式的工作表替换逻辑。以下是可行的修改方案:
关键修改点
- 每个程序使用唯一工作表名:4个程序分别对应4个不同的工作表(比如按CSV类型命名,如
CSV_Stock、CSV_Bond等),从根源避免覆盖其他程序的数据。 - 统一使用
openpyxl引擎:xlsxwriter不支持追加模式,openpyxl是唯一支持Excel文件追加、工作表替换的引擎。 - 简化文件存在判断逻辑:利用
if_sheet_exists='replace'参数,自动处理工作表存在/不存在的情况,无需手动判断文件后分分支写逻辑。
修改后的单程序代码示例
以下是其中一个程序的代码,其他三个程序仅需修改sheet_name为不同名称即可:
import pandas as pd import os # 1. 给当前程序指定唯一的工作表名 sheet_name = "CSV_Type_A" excel_path = r"Y:\HedgeFundRecon\JAron\Output\JAronOutput.xlsx" # 2. 读取CSV生成df_list(此处为模拟,替换为你的实际读取逻辑) df_list = [pd.DataFrame({'col1': [1,2], 'col2': [3,4]}), pd.DataFrame({'col1': [5,6], 'col2': [7,8]})] row_pos = 1 # 3. 统一使用openpyxl引擎处理写入 try: # 文件已存在:追加模式,替换当前程序对应的工作表 with pd.ExcelWriter( excel_path, engine='openpyxl', mode='a', if_sheet_exists='replace', datetime_format='dd/mm/yyyy' ) as writer: for item in df_list: item.to_excel(writer, sheet_name=sheet_name, startrow=row_pos, index=False) row_pos += len(item) + 2 except FileNotFoundError: # 文件不存在:新建文件并写入 with pd.ExcelWriter( excel_path, engine='openpyxl', mode='w', datetime_format='dd/mm/yyyy' ) as writer: for item in df_list: item.to_excel(writer, sheet_name=sheet_name, startrow=row_pos, index=False) row_pos += len(item) + 2
额外优化建议
- 如果你的
df_list是多个需要合并到同一工作表的小DataFrame,可以直接合并后写入,简化代码:pd.concat(df_list).to_excel(writer, sheet_name=sheet_name, index=False) - 路径使用原始字符串(加
r前缀),避免转义字符导致的路径错误。 - 确保所有4个程序都使用相同的
openpyxl引擎,不要混用xlsxwriter。
内容的提问来源于stack exchange,提问作者iBeMeltin
相关产品推荐
相关产品推荐

