brainytwoo
brainytwoo

Reputation: 43

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.

Upvotes: 4

Views: 4057

Answers (2)

Chirag Bhansali
Chirag Bhansali

Reputation: 2252

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

Upvotes: 5

VeLKerr
VeLKerr

Reputation: 3157

You can use PyGsheets lib. It uses sheets API v4 on lower level.

my_worksheet.sort_range() function will help you but it has some specialities

  1. Numbering in start and end cells start with 1 but basecolumnindex starts with 0.
  2. You can pass the cell's address in 2 ways: text index (like "A3") or tuple with 2 elements (like (1, 3)). The second way doesn't work for me.
  3. The range limited by start and end cells should contain column passed in basecolumnindex

Upvotes: 2

Related Questions