首页 > 解决方案 > 身份验证、上传文件以驱动和编辑现有电子表格 -

问题描述

我需要在我的桌面应用程序中上传一些图像并编辑一些 Google 电子表格,并选择 PyDrive 来帮助我访问我的驱动器(当时似乎比常规的 Google API 更容易)。但是,我很难对现有电子表格进行更改,例如添加一个带有字符串的新行。

我能够将文件上传到云端硬盘中的正确文件夹,但是我还没有找到一种以良好方式编辑表格的方法(setContentString 替换了当前内容;但我需要更新内容/添加一个新行一个新字符串。“.GetContentString”似乎也没有按预期运行)。

应该怎么做?我是否需要下载电子表格并在 pandas(或类似的)中对其进行更改,或者我可以在线执行此操作吗?

请在下面找到我的代码:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from pydrive.files import GoogleDriveFile


# Try to load saved client credentials
gauth = GoogleAuth()

gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
    # Authenticate if they're not there
    gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
    # Refresh them if expired
    gauth.Refresh()
else:
    # Initialize the saved creds
    gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("mycreds.txt")

drive = GoogleDrive(gauth)

def uploadImage(typeInput ,imgFile, listInput):
    # Determine the folder ID
    if type == "Type1":
        folderID ="folderID1"
    elif type == "Type2":
        folderID = "folderID2"


    str1 = "\'" + folderID + "\'" + " in parents and trashed=false"

    file_list = drive.ListFile({'q': str1}).GetList()
    imgTitles = []
    for file in file_list:
        q = (file['title'])
        imgTitles.append(q)
        # print(str(q))
    print(str(imgTitles))

    imgNr = imgTitles[0]
    imgNr = str(imgNr)[6:]
    imgNr = int(imgNr) + 1
    imgFileName = "Image_" + str(imgNr)

    imageToUpload = drive.CreateFile({'parents': [{'id': folderID}]})
    imageToUpload['title'] = imgFileName
    imageToUpload.SetContentFile(imgFile)
    imageToUpload.Upload()
    print('title: %s, id: %s' % (imageToUpload['title'], imageToUpload['id']))
    # call saveCoordsToTable
    addToTable(listInput, "typeInput", "imgFileName")


def addToTable(list_input, type_input, fileName_input):
    if type == "Type1":
        fileID = "folderID1"
    elif type == "Type2":
        fileID = "folderID2"


    folderID = "FolderIDxyz"  # The folder where the Google Sheets are

    str2 = "\'" + fileID + "\'" + " in parents and trashed=false"

    GSheet = drive.CreateFile({'q': str2})

    content = GSheet.GetContentString("test.csv")
    GSheet.SetContentString(content + str(list_input,
                                          type_input)  # Should take the current content and add a string to it. I probably need to specify somehow that it is a new row, but I have no idea how.
    GSheet.Upload()

uploadImage("Type1", img.png, [1, 2, 3, 4])

标签: pythonpython-3.xgoogle-sheetsgoogle-apipydrive

解决方案


您应该使用单独的库来编辑工作表。您可以使用 pygsheet 或直接使用 Google Sheets API。

对于 pygsheet,您可以使用insert_rowsappend_table添加带有值的行,而values.append用于 Google 表格。

Google 表格 API 示例:链接

参考:


推荐阅读