Search code examples
pythongoogle-sheets-apigspread

Using gspread to extract sheet ID


Can't seem to find any answer to this, but are there any functions/methods which can get a worksheet ID?

Currently, my code looks like this:

scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']

        ....code to authorize credentials goes here....

        sheet = client.open(str(self.googleSheetFile)).worksheet(str(self.worksheet))

        client.import_csv('abcdefg1234567abcdefg1234567', contents)

but I don't want to hardcode the abcdefg1234567abcdefg1234567. Is there anything I can do, like sheet.id()?


Solution

  • I believe your goal as follows.

    • In order to use import_csv, you want to retrieve the Spreadsheet ID from sheet = client.open(str(self.googleSheetFile)).worksheet(str(self.worksheet)).
    • You want to achieve this using gspread with python.

    In this case, you can retrieve the Spreadsheet ID from client.open(str(self.googleSheetFile)). So please modify your script as follows.

    From:

    sheet = client.open(str(self.googleSheetFile)).worksheet(str(self.worksheet))
    
    client.import_csv('abcdefg1234567abcdefg1234567', contents)
    

    To:

    spreadsheet = client.open(str(self.googleSheetFile))
    sheet = spreadsheet.worksheet(str(self.worksheet))
    client.import_csv(spreadsheet.id, contents)
    

    Note:

    • When I saw the document of gspread, it says as follows. So please be careful this.

      This method removes all other worksheets and then entirely replaces the contents of the first worksheet.

    • This modified script supposes that you have already been able to get and put values for Google Spreadsheet using Sheets API with gspread.

    Reference: