Search code examples
pythongoogle-drive-api

I can't read google drive's data(.xlsx) from local PC


I want read google drive's data(.xlsx) from local PC. However, the following error is returned and it cannot be read properly. Do you know the reason?

  • error
HttpError: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/<file_id>/export?mimeType=application%2Fvnd.openxmlformats-officedocument.spreadsheetml.sheet&alt=media returned "Export only supports Docs Editors files.". Details: "[{'domain': 'global', 'reason': 'fileNotExportable', 'message': 'Export only supports Docs Editors files.'}]">
  • code
if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)

service = build('drive', 'v3', credentials=creds)
file_id = '###'

request = service.files().export_media(fileId=file_id, mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
fh = io.FileIO('test.xlsx', mode='wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%." % int(status.progress() * 100))

Solution

  • From the error message Export only supports Docs Editors files, export_media can only be used for Google Workspace files, while you are trying to export an xlsx file. Instead you can try get_media API.

    See https://developers.google.com/drive/api/v3/manage-downloads#python