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

如何为pandas保存Excel文件的操作添加进度条?

pandas保存大体积Excel文件的进度展示方案

方案1:直接使用tqdm的pandas集成

你现有代码的问题是tqdm_gui.pandas()调用位置错误,该方法通过猴子补丁替换pandas的内置方法实现进度埋点,必须在to_excel调用前执行:

import os
import pandas as pd
from tqdm.gui import tqdm_gui

# 提前注册tqdm补丁,放在所有pandas IO操作前
tqdm_gui.pandas(desc="保存进度")

writer = pd.ExcelWriter(os.path.join(output_folder,"output.xlsx"),
                    strings_to_numbers=True)
final_df.to_excel(writer, header=True, index=False)
writer.save()

方案2:分块写入实现精准进度控制

如果数据量极大,想要更准确的进度预估和剩余时间展示,可以将DataFrame拆分为固定大小的块逐块写入,每完成一块更新一次进度:

import os
import pandas as pd
from tqdm import tqdm

# 可根据实际数据量调整单块行数,块越小进度展示越精细
chunk_size = 1000
total_rows = len(final_df)

writer = pd.ExcelWriter(os.path.join(output_folder,"output.xlsx"),
                    strings_to_numbers=True)
# 先写入表头
final_df.head(0).to_excel(writer, header=True, index=False)

with tqdm(total=total_rows, desc="保存进度") as pbar:
    for start in range(0, total_rows, chunk_size):
        end = min(start + chunk_size, total_rows)
        # 跳过表头,从第二行开始追加写入数据块
        final_df.iloc[start:end].to_excel(writer, header=False, index=False, startrow=start+1)
        pbar.update(end - start)

writer.save()

额外优化建议

  • 写入大文件时可以给pd.ExcelWriter添加engine='openpyxl', engine_kwargs={'write_only': True}参数,开启只写模式大幅提升写入速度
  • 要解决用户提前点击文件提示损坏的问题,可以先写入后缀为.tmp的临时文件,写入完成后再重命名为正式的.xlsx文件,避免用户在写入过程中访问到不完整的文件:
tmp_path = os.path.join(output_folder, "output.xlsx.tmp")
final_path = os.path.join(output_folder, "output.xlsx")

# 先写入临时文件
writer = pd.ExcelWriter(tmp_path, strings_to_numbers=True)
final_df.to_excel(writer, header=True, index=False)
writer.save()

# 写入完成后重命名为正式文件
if os.path.exists(final_path):
    os.remove(final_path)
os.rename(tmp_path, final_path)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:51:03