如何将pandas的DataFrame导出到Excel新工作表且不删除已有工作表
问题原因
你使用的xlsxwriter引擎本身不支持对已有Excel文件的修改操作,默认会直接创建全新的Excel文件覆盖原文件,因此原有工作表会全部丢失。
解决方法
需要切换为支持追加写入的openpyxl引擎实现需求,操作步骤如下:
先安装依赖包:
pip install openpyxl按pandas版本选择对应代码:
pandas 1.4.0及以上版本(推荐)
直接使用ExcelWriter原生追加模式即可:
import pandas as pd with pd.ExcelWriter(file_path, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer: df1.to_excel(writer, sheet_name='test1', index=False)
参数说明:
mode='a':指定为追加模式,不会清空原有文件内容if_sheet_exists:处理目标工作表名已存在的场景,可选值:'error':默认值,存在同名工作表则抛出错误'replace':直接覆盖原同名工作表'new':自动给新工作表重命名(例如test1自动改为test11)
1.4.0以下版本pandas兼容写法
如果使用低版本pandas,没有if_sheet_exists参数,可以用以下写法:
import pandas as pd from openpyxl import load_workbook # 先加载原有工作簿 book = load_workbook(file_path) writer = pd.ExcelWriter(file_path, engine='openpyxl') # 绑定原有工作簿 writer.book = book # 注册原有工作表到writer实例,避免被覆盖 writer.sheets = {ws.title: ws for ws in book.worksheets} df1.to_excel(writer, sheet_name='test1', index=False) writer.save() writer.close()
注意事项
- 操作前建议先备份原Excel文件,避免误操作丢失数据
- 如果原Excel是加密状态,需要先解密才能执行追加写入操作
内容的提问来源于stack exchange,提问作者MDJ
相关产品推荐
相关产品推荐

