简体   繁体   中英

Accessing a spreadsheet on Google Sheets using python3


I'm trying to read from a personal spreadsheet using the google api (v4) for spreadsheets.
I copied the code from the example google is providing while changing the spreadsheet id, range name and scope.
No matter what I do (make the spreadsheet public etc) I'm getting an HttpError: 404 Requested entity was not found.

My Code:

import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly',
        'https://www.googleapis.com/auth/spreadsheets',
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/drive.readonly']
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'python'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
            'sheets.googleapis.com-python.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store, None)
    return credentials

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
            'version=v4')
    service = discovery.build('sheets', 'v4', http = http,
            discoveryServiceUrl = discoveryUrl)
    spreadsheetId = 'ID'
    rangeName = 'RANGE'
    result = service.spreadsheets().values().get(
            spreadsheetId = spreadsheetId, range = rangeName).execute()

You haven't set a file/spreadsheet ID nor a valid cell range. You've also got a lot of extra code, likely including more scopes than you need. Here's a shorter one you can borrow that just dumps out the contents of a Sheet, only needing the RO-scope:

from pprint import pprint

from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
SHEETS = discovery.build('sheets', 'v4', http=creds.authorize(Http()))

SHEET_ID = 'YOUR_SHEET_DRIVE_FILE_ID'
rows = SHEETS.spreadsheets().values().get(spreadsheetId=SHEET_ID,
    range='Sheet1', fields='values').execute().get('values', [])
pprint(rows)

Before you run it (it'll run on both Python 2 & 3 without modification), make sure you've...

If you're still getting any kind of error, please post it as an update to the OP above. FWIW, I've made several videos demonstrating other uses of the Sheets API in case additional code samples help.

(All newer videos will be part of this video series which focuses on various G Suite APIs.)

Seeing quite a lot of boilerplate code in the question and the previous answer for a seemingly simple task I would like to share my recipe for this using pygsheets .

To be able to access Google Sheets API from Python script, I have registered on Google API Dashboard and have chosen Signed Credentials option described in Authorizing pygsheets .

I have downloaded a json file with credentials from Google API and saved it in the same directory as my Python script. The json file contains a dedicated email address that looks like

x-...updater@x...updater.iam.gserviceaccount.com

For the script to be able to access my Google sheet I have shared my sheet (used the default setting 'Can edit') with the email address contained in the json file.

Then the Python code to access the Google sheets could look like this:

import pygsheets
import pandas as pd

gc = pygsheets.authorize(service_file='service_creds.json')
sh = gc.open('Export Data')
wks_export = sh.worksheet(property='title', value='Export by Month')

# Google worksheet as Pandas dataframe.   
export_df = wks_export.get_as_df()

# Here can be done some local operations on the dataframe.

# Updating the worksheet with the values from the modified dataframe.
wks_export.set_dataframe(export_df, start='A1', fit=True)  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM