There seems to be no built-in function to sort within openpyxl but the function below will sort rows given some criteria:
def sheet_sort_rows(ws, row_start, row_end=0, cols=None, sorter=None, reverse=False):
""" Sorts given rows of the sheet
row_start First row to be sorted
row_end Last row to be sorted (default last row)
cols Columns to be considered in sort
sorter Function that accepts a tuple of values and
returns a sortable key
reverse Reverse the sort order
"""
bottom = ws.max_row
if row_end == 0:
row_end = ws.max_row
right = get_column_letter(ws.max_column)
if cols is None:
cols = range(1, ws.max_column+1)
array = {}
for row in range(row_start, row_end+1):
key = []
for col in cols:
key.append(ws.cell(row, col).value)
array[key] = array.get(key, set()).union({row})
order = sorted(array, key=sorter, reverse=reverse)
ws.move_range(f"A{row_start}:{right}{row_end}", bottom)
dest = row_start
for src_key in order:
for row in array[src_key]:
src = row + bottom
dist = dest - src
ws.move_range(f"A{src}:{right}{src}", dist)
dest += 1
Call it with the worksheet and start row to be sorted as a minimum. By default it'll sort on all columns A...max in that order but this can be changed by passing a 'cols' list. E.g. [4, 2] will sort first on D then on B.
Sort order can be reversed using 'reverse' as with 'sorted()'.
If you need more complex sorting, provide a 'sorter' function. This receives a tuple of values (being those from the 'cols' columns) and should return a sortable key.
It works by ascertaining the desired final destination of each row, moving them all down below the current worksheet, then moving them back to the required destination.
I wanted all columns in each row, but modifying to move a smaller area can be accomplished by changing the two calls to ws.move_range().
Examples:
sheet_sort_rows(ws, 5, 10) # Sort rows 5-10 using key: A, B, C, ...
sheet_sort_rows(ws, 5, 10, [2, 1]) # Sort rows using B, A
sheet_sort_rows(ws, 5, 10, [2, 1], reverse=True) # As above in reverse
def sorter(t):
return t[1] + " " + t[0][::-1]
sheet_sort_rows(ws, 5, 10, sorter=sorter)
This last sorts by column B followed by column A reversed.