身份验证,上传文件以驱动和编辑现有电子表格 -



我需要上传一些图片&在我的桌面应用程序中编辑一些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])

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

对于pygsheet,您可以使用insert_rows和append_table来添加带有值和值的行。

Google Sheets API示例:link

引用:

  • pygsheets
  • Google Sheets API

最新更新