1

Given a url of googlesheets like https://docs.google.com/spreadsheets/d/1dprQgvpy-qHNU5eHDoOUf9qXi6EqwBbsYPKHB_3c/edit#gid=1139845333 How could I use gspread api to get the name of the sheet? I mean the name may be sheet1, sheet2, etc Thanks!

Tanaike
  • 181,128
  • 11
  • 97
  • 165
jason
  • 7
  • 5

1 Answers1

1

I believe your goal is as follows.

  • You want to retrieve the sheet names from a Google Spreadsheet from the URL of https://docs.google.com/spreadsheets/d/###/edit#gid=1139845333.
  • From How could I use gspread api to get the name of the sheet?, you want to achieve this using gsperad for python.

In this case, how about the following sample script?

Sample script:

client = gspread.authorize(credentials)

url = "https://docs.google.com/spreadsheets/d/1dprQgvpy-qHNU5eHDoOUf9qXi6EqwBbsYPKHB_3c/edit#gid=1139845333"
spreadsheet = client.open_by_url(url)
sheet_names = [s.title for s in spreadsheet.worksheets()]
print(sheet_names)
  • In this script, please use your client = gspread.authorize(credentials).

  • When this script is run, the sheet names are returned as a list.

References:

Added:

About your following new question,

May I know what if I only want the sheet name of a particular one? Usually, for each additional sheet we create, it comes with a series of number at the end (gid=1139845333), I just want the name for that sheet instead of all.

In this case, how about the following sample script?

Sample script:

client = gspread.authorize(credentials)

url = "https://docs.google.com/spreadsheets/d/1dprQgvpy-qHNU5eHDoOUf9qXi6EqwBbsYPKHB_3c/edit#gid=1139845333"
gid = "1139845333"
sheet_name = [s.title for s in spreadsheet.worksheets() if str(s.id) == gid]
if len(sheet_name) == 1:
    print(sheet_name)
else:
    print("No sheet of the GID " + gid)
Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • Hi Tanaike, Thank you for your response! May I know what if I only want the sheet name of a particular one? Usually, for each additional sheet we create, it comes with a series of number at the end (gid=1139845333), I just want the name for that sheet instead of all. Thank you so much! – jason Nov 17 '21 at 15:29
  • @jason Thank you for replying. About your new question, I added one more sample script. Could you please confirm it? If that was not useful, I apologize. – Tanaike Nov 17 '21 at 23:28