👉 项目官网:https://www.python-office.com/ 👈

github star

大家好,这里是程序员晚枫,正在all in AI编程实战

你的程序跑起来黑屏一片,不知道进行到哪了?

今天教你怎么用 python-office 的进度条工具,让程序运行过程可视化。

1、最简单的进度条

1
2
3
4
5
6
import office

# 处理100个任务,显示进度
for i in range(100):
# 做你的工作...
office.progress.bar(i + 1, 100)

运行后,会显示:

1
Processing: [██████░░░░] 60%

2、彩色进度条

1
2
3
4
5
6
7
8
9
import office

# 彩色进度条
office.progress.bar(
current=50,
total=100,
color='green', # green/red/blue/yellow
desc='处理中'
)

3、自动进度条(循环版)

1
2
3
4
5
6
7
8
9
10
11
12
import office

# 处理1000个任务
tasks = range(1000)

for i, task in enumerate(tasks):
# 模拟处理
import time
time.sleep(0.01)

# 显示进度
office.progress.bar(i + 1, len(tasks), desc=f'处理任务 {i + 1}')

4、百分比显示

1
2
3
4
5
6
7
8
9
import office

# 显示百分比
for i in range(100):
office.progress.print(
current=i + 1,
total=100,
percentage=True
)

输出:

1
60/100 (60%)

5、实战案例:批量处理文件显示进度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import office
import os

def batch_process_with_progress(folder):
"""批量处理文件并显示进度"""
files = [f for f in os.listdir(folder) if f.endswith('.xlsx')]
total = len(files)

print(f'开始处理 {total} 个文件...')

for i, file in enumerate(files):
# 处理文件
path = os.path.join(folder, file)
# office.excel.read(path=path) ...

# 显示进度
office.progress.bar(i + 1, total, desc=f'处理 {file}')

print(f'处理完成!共 {total} 个文件')

batch_process_with_progress('Excel文件夹')

6、实战案例:多任务进度管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import office

# 定义多个任务
tasks = [
{'name': '下载文件', 'total': 100},
{'name': '处理数据', 'total': 200},
{'name': '生成报告', 'total': 50}
]

# 创建进度管理器
manager = office.progress.Manager()

for task in tasks:
manager.add_task(task['name'], task['total'])

# 模拟执行
import random
while not manager.is_complete():
task_name = manager.get_current_task()
manager.update(1)
import time
time.sleep(0.1)

print('所有任务完成!')

7、常见问题

Q:进度条显示位置不对?

A:在 Jupyter Notebook 中效果最佳,普通终端可能需要加 \r 换行。

Q:进度条卡住不动?

A:确保 update 在循环中被调用,且 total 值正确。

Q:能自定义样式吗?

A:可以:

1
2
3
4
5
6
7
office.progress.bar(
current=50,
total=100,
bar_length=50, # 进度条长度
fill='█',
suffix='{percent}%'
)

8、下讲预告

学会了进度条,下一讲我们学 综合实战:做一个自动化办公助手

敬请期待!


有问题欢迎加微信 python-office 进群交流~

程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!