从Python在Google Sheet中附加一个列表

时间:2017-09-18 07:41:54

标签: python google-sheets-api

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

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

我对如何以一种简单的方式做到这一点没有任何线索。

6 个答案:

答案 0 :(得分:6)

这个示例脚本怎么样?此示例将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的详细信息。

如果这个样本对你没用,我很抱歉。

答案 1 :(得分:0)

您可以尝试这样的事情:

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:

  

更新需要有效的ValueInputOption参数(用于单数)   更新,这是一个必需的查询参数;对于批量更新,这个   请求正文中需要参数)。 ValueInputOption   控制是否解析输入字符串,如中所述   下表:

     

RAW输入未被解析,只是作为字符串插入,所以

     
    

输入" = 1 + 2"放置字符串" = 1 + 2"在细胞中,而不是一个公式。     (布尔值或数字之类的非字符串值始终处理为     RAW。)

  
     

USER_ENTERED输入的解析方式与输入完全相同

     
    

进入Google表格用户界面,所以" 2016年3月1日"成为约会," = 1 + 2"     成为一个公式。也可以推断出格式,所以" $ 100.15"变     带货币格式的数字。

  

答案 2 :(得分:0)

根据Google's official quickstart + @Tanaike的回答,我建议以下示例说明如何将行添加到工作表文档:


从URL中获取电子表格ID:

take the spreadsheet id from the url

脚本:

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>"

结果:
这是您连续多次运行脚本的样子

enter image description here

?请遵循Google's official quickstart并授予自己API权限并安装以下软件包:

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

答案 3 :(得分:0)

您可以使用 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

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

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

<td class="td" style="text-align:left; vertical-align:middle; border: 1px solid #eee; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;"><?php echo $order->get_formatted_line_subtotal( $item ); ?></td>

输出:(在 GoogleSheets 中)

enter image description here