Sorting with openpyxl

隐身守侯 提交于 2019-12-12 22:04:02

问题


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')

Any help is greatly appreciated!


回答1:


The openpyxl documentation clearly states:

This will add the relevant instructions to the file but will neither actually filter nor sort.

So you would need to compute the new sequence of rows and move the data explicitly (i.e. assigning the cells to their new positions).




回答2:


You can sort using win32com.client (install it with pip install pypiwin32).

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).

See these documentation links for more information about Sort() and its parameters:

  • Range.Sort()
  • XlSortOrientation
  • XlSortOrder
  • Better way to spawn excel process.


来源:https://stackoverflow.com/questions/44767554/sorting-with-openpyxl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!