简体   繁体   English

使用 Openpyxl 按值对 excel 列进行排序

[英]Sorting excel columns by value using Openpyxl

I did this in pandas with 2 lines of code but can't find an equivalent in Openpyxl, sadly I can't use pandas for this project.我在 pandas 中使用 2 行代码执行了此操作,但在 Openpyxl 中找不到等效项,遗憾的是我无法在此项目中使用 pandas。 My pandas code:我的 pandas 代码:

df = pd.read_excel('test2.xlsx')
first_n_rows = df.sort_values(by=['Min tries', 'Total min tries'], ascending=[True, False]).head(5)

I am trying to sort scores for a game by number of Minimum tries, and if 2 users have same number of Min tries, then sort by Total min tries descending.我正在尝试按最小尝试次数对游戏的分数进行排序,如果 2 个用户的最小尝试次数相同,则按总最小尝试次数降序排序。

Openpyxl is used to read and write Excel files. Openpyxl 用于读写 Excel 文件。 You can do it this way with win32com (if pandas is not allowed):你可以用 win32com 这样做(如果 pandas 是不允许的):

import win32com.client

excel = win32com.client.Dispatch("Excel.Application")

wb = excel.Workbooks.Open('MyWorkbook.xlsx')
ws = wb.Worksheets('Sheet1')

ws.Range('A2:A9').Sort(Key1=ws.Range('A1'), Key2=ws.Range('A1'), Order1=1, Order2=0, Orientation=1)

Change the pointer according to your excel根据您的 excel 更改指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM