Search code examples
python-3.xgoogle-sheetsgspread

Sort a spread sheet via gspread


I have a Google spreadsheet full of names, dates, and some other numbers. I made an desktop application that provides a nice UI for said info. After using the application a bit I became slightly annoyed with the order the data was being displayed.

I have been researching all day and I cannot seem to find anything on the topic of sorting the spreadsheet from a python script. All I need is some function that I can call every time someone adds something to it to re-sort the sheet.

I would very much appreciate it if someone could help me out.

Thanks in advance.


Solution

  • GSpread has a .sort() method to sort a worksheet using given sort orders. Here's how you can use it (Source - GSpread Docs):

    Parameters:

    • specs (list) – The sort order per column. Each sort order represented by a tuple where the first element is a column index and the second element is the order itself: ‘asc’ or ‘des’.
    • range (str) – The range to sort in A1 notation. By default sorts the whole sheet excluding frozen rows.

    Example:

    # Sort sheet A -> Z by column 'B'
    wks.sort((2, 'asc'))
    
    # Sort range A2:G8 basing on column 'G' A -> Z
    # and column 'B' Z -> A
    wks.sort((7, 'asc'), (2, 'des'), range='A2:G8')