You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pandas ExcelWriter创建Excel文件后适用的打印提示命令方法

解决方案

只需要在with上下文管理器代码块的外部添加打印提示即可——with块执行结束时,ExcelWriter会自动完成文件刷盘、资源释放操作,此时文件才是真正写入完成的状态,不会出现提示弹出但文件还没生成的时序问题。

基础修改版代码

import pandas as pd 

df = pd.DataFrame(data={'col1':[9,3,4,5,1,1,1,1], 'col2':[6,7,8,9,5,5,5,5]}) 
df2 = pd.DataFrame(data={'col1':[25,35,45,55,65,75], 'col2':[61,71,81,91,21,31]}) 

output_file = 'test.xlsx'
with pd.ExcelWriter(output_file, engine='xlsxwriter') as writer:
    df.to_excel(writer, sheet_name='testSheetJ', startrow=1, startcol=0)
    df2.to_excel(writer, sheet_name='testSheetJ', startrow=1+len(df)+3, startcol=0) 

# 此处文件已完全写入完成,添加提示
print(f"文件创建完成,已保存至:{output_file}")

增强版(带异常判断)

如果需要区分写入成功、失败的场景,可以搭配try/except结构做更明确的提示:

import pandas as pd 

df = pd.DataFrame(data={'col1':[9,3,4,5,1,1,1,1], 'col2':[6,7,8,9,5,5,5,5]}) 
df2 = pd.DataFrame(data={'col1':[25,35,45,55,65,75], 'col2':[61,71,81,91,21,31]}) 

output_file = 'test.xlsx'
try:
    with pd.ExcelWriter(output_file, engine='xlsxwriter') as writer:
        df.to_excel(writer, sheet_name='testSheetJ', startrow=1, startcol=0)
        df2.to_excel(writer, sheet_name='testSheetJ', startrow=1+len(df)+3, startcol=0) 
except Exception as err:
    print(f"文件创建失败,错误原因:{str(err)}")
else:
    print(f"✅ 文件创建完成,已保存至:{output_file},共写入2组数据到testSheetJ工作表")

注意事项

  • 不要把打印提示写在with块内部:块内代码执行时数据还停留在内存中,没有最终写入磁盘,此时弹出完成提示不符合实际执行状态。
  • 如果需要提示更丰富的信息,可以在打印语句中补充工作表名称、数据行数、文件大小等自定义内容。

内容的提问来源于stack exchange,提问作者Marianne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 06:18:17