用openpyxl排序 [英] Sorting with openpyxl
问题描述
我正在尝试使用openpyxl从最小到最大对列进行排序.我愿意使用其他库来完成此任务.这是我现在拥有的代码,但是没有排序.
I am trying to sort columns from least to greatest using openpyxl. I am open to using other libraries to accomplish this. Here is the code that I have right now, however, nothing is being sorted.
from openpyxl import load_workbook
wb=load_workbook('NotSorted.xlsx')
ws1=wb.get_sheet_by_name('Mean')
ws1.auto_filter.add_sort_condition('J2:J21')
wb.save('Sorted.xlsx')
任何帮助将不胜感激!
推荐答案
您可以使用win32com.client
进行排序(使用pip install pypiwin32
安装).
You can sort using win32com.client
(install it with pip install pypiwin32
).
名称为MyWorkbook.xlsx
的示例工作簿,其内容(前后):
Example workbook named MyWorkbook.xlsx
with contents (before and after):
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'), Order1=1, Orientation=1)
wb.Save()
excel.Application.Quit()
如果您不想更改原始工作簿,请使用(具有适当的范围).
If you don't want to alter the original workbook, use SaveAs()
or create another workbook and copy data like so: ws_from.Range("A1:AF100").Copy(ws_to.Range("A1:AF100"))
(with appropriate range).
有关这些Sort()
及其参数的更多信息,请参见以下文档链接:
See these documentation links for more information about Sort()
and its parameters:
- Range.Sort()
- XlSortOrientation
- XlSortOrder
- Better way to spawn excel process.
这篇关于用openpyxl排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!