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

大家好,这里是程序员晚枫,正在all in AI编程实战。
今天教你怎么用代码筛选和排序Excel数据,比手动操作快100倍!
1、自动筛选
给 Excel 添加筛选功能:
1 2 3 4 5 6 7
| import office
office.excel.filter( path='数据表.xlsx', range='A1:E100' )
|
打开 Excel 后,点击表头的下拉箭头就可以筛选了。
2、按条件筛选数据
筛选出满足条件的数据,保存到新文件:
1 2 3 4 5 6 7 8 9 10 11 12 13
| import office import pandas as pd
df = office.excel.read(path='员工表.xlsx')
df_filtered = df[df['部门'] == '销售部']
office.excel.write(path='销售部员工.xlsx', data=df_filtered)
print(f'筛选完成!共 {len(df_filtered)} 人')
|
3、多条件筛选
1 2 3 4 5 6 7 8 9
| import office import pandas as pd
df = office.excel.read(path='销售表.xlsx')
df_filtered = df[(df['销售额'] > 10000) & (df['地区'] == '北京')]
office.excel.write(path='北京高销售额.xlsx', data=df_filtered)
|
4、排序数据
按销售额从高到低排序:
1 2 3 4 5 6 7 8 9
| import office import pandas as pd
df = office.excel.read(path='销售表.xlsx')
df_sorted = df.sort_values(by='销售额', ascending=False)
office.excel.write(path='销售排名.xlsx', data=df_sorted)
|
多列排序:
1 2
| df_sorted = df.sort_values(by=['部门', '销售额'], ascending=[True, False])
|
5、数据验证
给单元格添加下拉菜单:
1 2 3 4 5 6 7 8 9
| import office
office.excel.validation( path='信息表.xlsx', cell='B1:B100', type='list', formula='北京,上海,广州,深圳' )
|
数值范围验证:
1 2 3 4 5 6 7 8
| office.excel.validation( path='成绩表.xlsx', cell='C1:C100', type='whole', minimum=0, maximum=100 )
|
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 import pandas as pd
def filter_top_customers(excel_file, threshold=10): """筛选出订单数超过阈值的客户""" df = office.excel.read(path=excel_file) order_count = df.groupby('客户名')['订单号'].count().reset_index() order_count.columns = ['客户名', '订单数'] top_customers = order_count[order_count['订单数'] >= threshold] result = df[df['客户名'].isin(top_customers['客户名'])] office.excel.write(path='高频客户.xlsx', data=result) print(f'筛选完成!共 {len(top_customers)} 个高频客户,{len(result)} 条订单')
filter_top_customers('订单表.xlsx', threshold=5)
|
7、实战案例:自动生成各地区销售报表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import office import pandas as pd import os
def generate_regional_reports(excel_file): """按地区自动生成销售报表""" df = office.excel.read(path=excel_file) regions = df['地区'].unique() os.makedirs('分地区报表', exist_ok=True) for region in regions: region_df = df[df['地区'] == region] region_df = region_df.sort_values(by='销售额', ascending=False) filename = f'分地区报表/{region}销售报表.xlsx' office.excel.write(path=filename, data=region_df) print(f'已生成: {filename}') print(f'共生成 {len(regions)} 个地区报表!')
generate_regional_reports('全国销售表.xlsx')
|
8、常见问题
Q:筛选条件太复杂怎么办?
A:用 pandas 的高级筛选,功能最强。
Q:排序后想恢复原始顺序?
A:加一列序号,排序后再按序号排回来。
Q:下拉菜单不生效?
A:确保选项用英文逗号分隔,不要有空格。
9、下讲预告
学会了筛选排序,下一讲我们学 Word高级格式:表格、页眉页脚、目录。
敬请期待!
有问题欢迎加微信 python-office 进群交流~
程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。
🎓 AI 编程实战课程
想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!