python - 如何使用 Drive API 和 Python 中的服务帐户将电子表格中的所有工作表导出为 CSV 文件?

标签 python google-api google-sheets-api google-api-python-client service-accounts

我已经成功建立了与 Drive API 的服务连接,并且我正在创建导出 URL,通过使用 Google 的 AuthorizedSession 类发送请求,将电子表格中的每个工作表下载为 CSV 文件。出于某种原因,只有一部分 CSV 文件返回正确,而其他文件包含损坏的 HTML。当我发送单个请求时,工作表总是返回正确的,但是当我遍历工作表并开始发送请求时,事情开始中断。我发现我以这种方式传递凭据的方式存在问题,但我不确定我是否正确使用了 AuthorizedSession。谁能帮我解决这个问题?

from googleapiclient.discovery import build
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
import re
import shutil
import urllib.parse


CLIENT_SECRET_FILE = "client_secret.json"
API_NAME = "sheets"
API_VERSION = "v4"
SCOPES = ["https://www.googleapis.com/auth/drive.readonly"]
SPREADSHEET_ID = "Spreadsheet ID goes here"
print(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES, sep="-")

cred = service_account.Credentials.from_service_account_file(
    CLIENT_SECRET_FILE, scopes=SCOPES
)

try:
    service = build(API_NAME, API_VERSION, credentials=cred)
    print(API_NAME, "service created successfully")
    result = service.spreadsheets().get(spreadsheetId=SPREADSHEET_ID).execute()
    export_url = re.sub("\/edit$", "/export", result["spreadsheetUrl"])
    authed_session = AuthorizedSession(cred)

    for sheet in result["sheets"]:
        sheet_name = sheet["properties"]["title"]
        params = {"format": "csv", "gid": sheet["properties"]["sheetId"]}
        query_params = urllib.parse.urlencode(params)
        url = export_url + "?" + query_params
        response = authed_session.get(url)

        file_path = "./Downloads/" + sheet_name + ".csv"
        with open(file_path, "wb") as csv_file:
            csv_file.write(response.content)
            print("Downloaded sheet: " + sheet_name)
    print("Downloads complete")
except Exception as e:
    print("Unable to connect")
    print(e)

最佳答案

此代码应该为您提供表格服务

"""Hello sheets."""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


SCOPES = ['"https://www.googleapis.com/auth/drive.readonly']
KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'


def initialize_sheet():
  """Initializes an sheetservice object.

  Returns:
    An authorized sheetservice object.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  sheet= build('sheet', 'v4', credentials=credentials)

  return sheet

如果您使用通过此方法构建的相同工作表服务,那么您不会有任何循环问题

关于python - 如何使用 Drive API 和 Python 中的服务帐户将电子表格中的所有工作表导出为 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65780803/

相关文章:

python - 使用 continue 跳过迭代列表中的 "double iterator"循环

java - 使用 Google Calendar API 和服务帐户创建 Activity

php - GMail API - 如何显示收件箱中的完整电子邮件

google-api - 来自 Google API 的电影放映时间和 map

javascript - 如何在不需要用户登录的情况下在网站上使用 Google 表格中的数据?

python - 在 CentOS 上使用 Python 脚本连接 MySQL

python - 如何通过更新 OrderedDict 来保持订单

python - 为什么我在 Robot Framework IDE (RIDE) 中使用 pymssql 连接到数据库时出现错误?

javascript - 将我的 Chrome 扩展程序中的表单数据写入 Google 表格

node.js - 从 Google App Engine - NodeJS Flexible Environment 访问 Google 表格和 Google 的非云平台 API