首页 > 解决方案 > 电子表格 API - 当电子表格在某些列中有公式时附加值

问题描述

我正在使用电子表格 api 将值附加到工作表,但此工作表有一个特殊性,它有一些带有公式的列,用于处理我应该在其他列中引入的数据,所以我不能删除这些列,但是当我尝试附加一个值时,该值被附加到最后,其中未定义公式,带有公式的列使我的代码跳过行,直到没有公式,这是我的一段代码用于附加

import os
import pickle
import os.path
import io
import shutil

from lector_nombre import lectorNombre
from Tablas import lectorTablas
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload

SCOPES = ['https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/spreadsheets']

#SAMPLE_SPREADSHEET_ID = '1BxiMVs0ew23gmUUqptlb23frvfvE2upms'
#SAMPLE_RANGE_NAME = 'Class Data!A2:E'

"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

service = build('sheets', 'v4', credentials=creds)

# Call the Sheets API
sheet = service.spreadsheets()

data=[["data","data","data","data","https://google.com"]]
res = sheet.values().append(spreadsheetId="134542fvbvfdfewdvwed4",
                            range="sheet!A1:G1",
                            valueInputOption="USER_ENTERED",
                            insertDataOption="INSERT_ROWS",
                            body={"values":data}).execute()
print(res)

这里有一张我的工作表看起来如何的图像在此处输入图像描述

编辑:

我想我的问题并不是很清楚,我真正需要的是指定一个范围,让我可以在我想要的地方写下,而不会因为公式的原因而跳过行

标签: pythongoogle-sheetsgoogle-drive-apigoogle-sheets-api

解决方案


您正在使用 电子表格附加值.values.append您基本上是在添加一个新行并设置其数据。

您需要使用电子表格.values.update,它允许您修改电子表格范围内的值,而无需添加新的行或列。

例子:

在此处输入图像描述

输出:

在此处输入图像描述


推荐阅读