从 Python Google Sheet 中追加一个列表

Append a list in Google Sheet from Python

我在 Python 中有一个列表,我只想在 Google Sheet 的第一列中逐行写入(追加)。我完成了所有初始身份验证部分,这是代码:

credentials = GoogleCredentials.get_application_default()
service = build('sheets', 'v4', credentials=credentials)

我不知道如何以简单的方式做到这一点。

这个示例脚本怎么样?此示例将 list 附加到 A 列。作为数据的列表是二维数组。请注意这一点。要使用此脚本,请在 API 控制台启用 Sheet API v4。

示例脚本:

credentials = GoogleCredentials.get_application_default()
service = build('sheets', 'v4', credentials=credentials)

list = [["valuea1"], ["valuea2"], ["valuea3"]]
resource = {
  "majorDimension": "ROWS",
  "values": list
}
spreadsheetId = "### spreadsheet ID"
range = "Sheet1!A:A";
service.spreadsheets().values().append(
  spreadsheetId=spreadsheetId,
  range=range,
  body=resource,
  valueInputOption="USER_ENTERED"
).execute()

您可以在here查看spreadsheets.values.append的详细信息。

如果此示例对您没有用,我很抱歉。

您可以尝试这样的操作:

credentials = GoogleCredentials.get_application_default()
service = build('sheets', 'v4', credentials=credentials)
spreadsheet_id = "give the spreadsheet ID of the sheet you want to append to"
range_name = "specify the range you are looking at eg: A1:B1"

values = [
   [list of cell values per row]
   [additional rows of data]
]

body = {
'values': values
}

result = service.spreadsheets().values().update(
    spreadsheetId=spreadsheet_id, range=range_name,
    valueInputOption=value_input_option, body=body).execute()

来自 docs:

Updates require a valid ValueInputOption parameter (for singular updates, this is a required query parameter; for batch updates, this parameter is required in the request body). The ValueInputOption controls whether input strings are parsed or not, as described in the following table:

RAW The input is not parsed and is simply inserted as a string, so the

input "=1+2" places the string "=1+2" in the cell, not a formula. (Non-string values like booleans or numbers are always handled as RAW.)

USER_ENTERED 输入的解析与输入时完全一样

into the Google Sheets UI, so "Mar 1 2016" becomes a date, and "=1+2" becomes a formula. Formats may also be inferred, so "0.15" becomes a number with currency formatting.

根据 Google's official quickstart + 的回答,我建议使用以下示例来说明如何将行附加到 Sheet 文档:


从 URL:

中获取电子表格 ID

脚本:

import os
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SHEETS_READ_WRITE_SCOPE = 'https://www.googleapis.com/auth/spreadsheets'
SCOPES = [SHEETS_READ_WRITE_SCOPE]


def main():
    spreadsheet_id = '1TfWKWaWypbq7wc4gbe2eavRBjzuOcpAD028CH4esgKw'  # this is part of the url of google
    rows = [
        ["Hello World", "שלום עולם ינעל העולם", ":)"],
        ["Hello"],
        ["World"]
    ]

    # -----------

    credentials = get_or_create_credentials(scopes=SCOPES)  # or use GoogleCredentials.get_application_default()
    service = build('sheets', 'v4', credentials=credentials)
    service.spreadsheets().values().append(
        spreadsheetId=spreadsheet_id,
        range="Sheet1!A:Z",
        body={
            "majorDimension": "ROWS",
            "values": rows
        },
        valueInputOption="USER_ENTERED"
    ).execute()


# Source: https://developers.google.com/sheets/api/quickstart/python
def get_or_create_credentials(scopes):
    credentials = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            credentials = pickle.load(token)
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', scopes)
            credentials = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(credentials, token)
    return credentials


if __name__ == '__main__':
    main()

  • 记得改 - spreadsheet_id = "<your spreadsheet document id>"

结果:
如果您连续多次运行脚本

,这就是它的样子

请遵循 Google's official quickstart 并授予自己 API 权限 + 安装这些软件包:

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib 

您可以使用 pandas + gspread 将列表导出为单列数据框。

import pandas as pd
import gspread
from gspread_dataframe import set_with_dataframe
from oauth2client.client import GoogleCredentials as GC
my_list = ['apple', 'banana', 'orange']
df_my_list = pd.DataFrame(data=my_list[1:], columns=[my_list[0]])
gc = gspread.authorize(GC.get_application_default())
doc = gc.open_by_key(document_id)
document_id = # YOUR DOCUMENT ID
worksheet_name = 'my_list'
# Try to update current worksheet, or create a new one
try: 
  sheet = doc.worksheet(worksheet_name)
except:
  sheet = doc.add_worksheet(worksheet_name, rows=1, cols=1)
set_with_dataframe(sheet, df_my_list, resize=True)

有关 Python 到 Google 表格的更多信息,您可以查看此 article

您可以将 cell_values 转换为 pandas 数据框,然后使用 gspread_dataframe.set_with_dataframe 将其导出到 Google 表格。它不会导致任何配额问题,因为它会立即发送完整的数据帧。

import pandas as pd
import gspread
from gspread_dataframe import set_with_dataframe
from oauth2client.client import GoogleCredentials as GC
df = # YOUR DATAFRAME
document_id = # YOUR DOCUMENT ID
worksheet_name = # YOUR WORKSHEET NAME
gc = gspread.authorize(GC.get_application_default())
doc = gc.open_by_key(document_id)
# Update existing spreadsheet or create a new one
try: 
  sheet = doc.worksheet(worksheet_name)
except:
  sheet = doc.add_worksheet(worksheet_name, rows=1, cols=1)
set_with_dataframe(sheet, df, resize=True)

有关 Python 至 Google 表格的更多信息,您可以查看此 article

此代码将列表列表附加到 google 工作表中的每一列。 my_list作为数据是一个二维数组。

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request


class spreadSheetLogger:
    def __init__(self, sheetName):
        SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
        credentials = config_file.get_google_credentials()
        # The ID and range of a sample spreadsheet.
        SAMPLE_SPREADSHEET_ID = '################'
        SAMPLE_RANGE_NAME = '{}!A:A'.format(sheetName, "DefaultName")
        service = build('sheets', 'v4', credentials=self.creds)
        sheet = self.service.spreadsheets()

    def spreadLogger(self, message, requestJson, timestamp)
        my_list = [[message], [str(timestamp)], [str(requestJson)]]
        body = {
            "majorDimension": "COLUMNS",
            "values": my_list
        }

        request = self.service.spreadsheets().values().append(spreadsheetId=self.SAMPLE_SPREADSHEET_ID,range=self.SAMPLE_RANGE_NAME,valueInputOption='RAW', body=body)
        response = request.execute()
        return "Record Inserted Successfully"

输出:(在 GoogleSheets 中)