如何导出pandas DataFrame至Excel且不删除原有工作表
导出Excel时保留原有工作表的解决方法
问题根源:pandas默认的to_excel()方法会直接覆盖整个Excel文件,导致原有工作表被删除。要保留其他工作表,需要使用追加模式写入。
具体实现代码
读取数据的代码保持不变:
import pandas as pd df1 = pd.read_excel('Portfolio.xlsx', sheet_name='Input') # 这里是你的数据分析逻辑,最终生成df2
导出部分修改为以下代码:
# 用追加模式打开文件,指定openpyxl引擎(仅支持.xlsx格式) with pd.ExcelWriter('Portfolio.xlsx', mode='a', engine='openpyxl', if_sheet_exists='replace') as writer: df2.to_excel(writer, sheet_name='Output', index=False)
参数说明
mode='a':开启追加模式,不会覆盖原有文件中的其他工作表engine='openpyxl':必须指定该引擎,因为pandas默认的xlsxwriter不支持追加操作(需提前安装:pip install openpyxl)if_sheet_exists='replace':若Output工作表已存在,则替换原有内容;若希望保留旧表并新建(Excel不允许重名,实际会报错),可改为'new',建议使用replaceindex=False:避免将DataFrame的索引列写入Excel,可按需调整
旧格式Excel(.xls)的处理
如果你的文件是.xls格式,openpyxl不支持,可通过以下方式处理:
- 优先将文件转成
.xlsx格式,使用上述方法更简便 - 若必须保留
.xls,可借助xlrd和xlutils库:
from xlrd import open_workbook from xlutils.copy import copy # 读取原有工作簿 wb = open_workbook('Portfolio.xls', formatting_info=True) wb_copy = copy(wb) # 获取要写入的工作表,不存在则新建 ws = wb_copy.get_sheet('Output') if 'Output' in wb.sheet_names() else wb_copy.add_sheet('Output') # 写入表头 for j, col in enumerate(df2.columns): ws.write(0, j, col) # 将df2逐行写入工作表 for i, row in enumerate(df2.values): for j, val in enumerate(row): ws.write(i+1, j, val) wb_copy.save('Portfolio.xls')
内容的提问来源于stack exchange,提问作者George Heisel
相关产品推荐
相关产品推荐

