当前位置:网站首页>【openpyxl】过滤和排序
【openpyxl】过滤和排序
2022-08-10 23:50:00 【冰冷的希望】
1.过滤和排序
如果你想对表格进行过滤或排序,openpyxl有提供对应的设置,但是,只是添加过滤排序选项,并不会真的操作数据,如果想要操作,还是得在Excel中手动点击
2.代码
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# 准备数据
rows = [
['月份', '桃子', '西瓜', '龙眼'],
[1, 38, 28, 29],
[2, 52, 21, 35],
[3, 39, 20, 69],
[4, 51, 29, 41],
[5, 39, 39, 31],
[6, 30, 41, 39],
]
for row in rows:
ws.append(row)
ws.auto_filter.ref = "A1:D7" # 选择数据范围
ws.auto_filter.add_filter_column(1, ["39", "29", "30"]) # 选择第2列为过滤数据(下标从0开始),并勾选需要过滤的数据项
ws.auto_filter.add_sort_condition("C2:C7", True) # 设置排序范围,第二个参数是是否倒序,默认为否
wb.save("./openpyxl/test.xlsx")
效果如下
3.pandas排序
虽然openpyxl不能真的实现排序,但是我们可以借助超级强大的pandas轻松实现排序
import pandas as pd
# 读取上一步保存的Excel文件
df = pd.read_excel("./openpyxl/test.xlsx", sheet_name="Sheet")
df_value = df.sort_values(by=["桃子", "西瓜"], ascending=False) # 如果"桃子"数据相同再按照"西瓜"进行排列
# 保存文件
writer = pd.ExcelWriter('./openpyxl/sort_file.xlsx')
df_value.to_excel(writer, sheet_name='Sheet1', index=False)
writer.save()
边栏推荐
- 力扣每日一题-第52天-387. 字符串中的第一个唯一字符
- 如何做专利挖掘,关键是寻找专利点,其实并不太难
- Web-based meal ordering system in epidemic quarantine area
- "NIO Cup" 2022 Nioke Summer Multi-School Training Camp 2 DGHJKL Problem Solution
- NOR FLASH闪存芯片ID应用之软件保护场景
- 鲜花线上销售管理系统的设计与实现
- SAS data processing technology (1)
- Design and implementation of flower online sales management system
- [C language] Implementation of guessing number game
- SQL注入基础---order by \ limit \ 宽字节注入
猜你喜欢
excel英文自动翻译成中文教程
地下管廊可视化管理系统搭建
3. 容器功能
Why do programming languages have the concept of variable types?
【C语言篇】表达式求值(隐式类型转换,算术转换)
Ali P7 bask in January payroll: hard to fill the, really sweet...
Where can I download IEEE papers?
How to recover data from accidentally deleted U disk, how to recover deleted data from U disk
鲲鹏编译调试及原生开发工具基础知识
宝塔实测-搭建PHP在线模拟考试系统
随机推荐
Dump文件生成,内容,以及分析
电脑桌面删除的文件回收站没有,电脑上桌面删除文件在回收站找不到怎么办
C language, operators of shift operators (> >, < <) explanation
[C] the C language program design, dynamic address book (order)
翻译软件哪个准确度高【免费】
关于科研学习中的几个问题:如何看论文?如何评价工作?如何找idea?
好用的翻译插件-一键自动翻译插件软件
【pypdf2】安装、读取和保存、访问页面、获取文本、读写元数据、加密解密
Timers, synchronous and asynchronous APIs, file system modules, file streams
How to recover data from accidentally deleted U disk, how to recover deleted data from U disk
[C language] Implementation of guessing number game
14. Thymeleaf
promise详解
How to determine how many bases a number is?
Is there a way out in the testing industry if it is purely business testing?
u盘数据不小心删除怎么恢复,u盘数据删除如何恢复
Which translation software is more accurate [Free]
Lens filter---about day and night dual-pass filter
excel英文自动翻译成中文教程
开启新征程——枫叶先生第一篇博客