简体   繁体   English

使用 GSpread 在文件夹中创建电子表格

[英]Creating A Spreadsheet In A Folder With GSpread

I am having trouble finding any documentation on how to create a GSheet in a certain Google Drive directory using GSpread.我无法找到有关如何使用 GSpread 在某个 Google Drive 目录中创建 GSheet 的任何文档。

I have checked the documentation and had a look around some of the back end code.我检查了文档并查看了一些后端代码。

I am currently using the code below to create the spreadsheet:我目前正在使用下面的代码来创建电子表格:

worksheet = sh.add_worksheet(title='Overview', rows='100', cols='9')

I want to be able to create the spreadsheet in a directory on a google drive, for example:我希望能够在谷歌驱动器的目录中创建电子表格,例如:

X > Y > Spreadsheet X > Y > 电子表格

Any help would be greatly appreciated,任何帮助将不胜感激,

Cheers.干杯。

  • You want to create new Spreadsheet to the specific folder.您想在特定文件夹中创建新的电子表格。
  • You want to achieve this using Python.您想使用 Python 来实现这一点。

If my understanding is correct, how about this answer?如果我的理解是正确的,这个答案怎么样?

Modification points:改装要点:

  • Unfortunately, Sheets API cannot achieve this.不幸的是,Sheets API 无法实现这一点。 In this case, it is required to use Drive API.在这种情况下,需要使用 Drive API。
  • In your script, I think that you use gspread.authorize() like gc = gspread.authorize(credentials) .在您的脚本中,我认为您使用gspread.authorize()就像gc = gspread.authorize(credentials) In this modification, credentials is used.在此修改中,使用credentials
  • The script in your question of worksheet = sh.add_worksheet(title='Overview', rows='100', cols='9') is used for adding a sheet to the existing Spreadsheet.您的worksheet = sh.add_worksheet(title='Overview', rows='100', cols='9')问题中的脚本用于向现有电子表格添加工作表。 When you create new Spreadsheet using gspread, please use sh = gc.create('A new spreadsheet') .当您使用 gspread 创建新电子表格时,请使用sh = gc.create('A new spreadsheet')
    • In this case, the new Spreadsheet is created to the root folder.在这种情况下,将在根文件夹中创建新的电子表格。

Preparation:准备:

Before you use the following script, please enable Drive API at API console, and please add the scope of https://www.googleapis.com/auth/drive .在使用以下脚本之前,请在 API 控制台启用 Drive API,并添加https://www.googleapis.com/auth/drive的范围。 If you are using the scope of https://www.googleapis.com/auth/drive.file , please use this and the scope is not required to be modified to https://www.googleapis.com/auth/drive .如果您使用的是https://www.googleapis.com/auth/drive.file的范围,请使用这个,范围不需要修改为https://www.googleapis.com/auth/drive

  • If you are using OAuth2, please remove the file including the refresh token.如果您使用的是 OAuth2,请删除包含刷新令牌的文件。 And then, please run the script and reauthorize again.然后,请运行脚本并再次重新授权。 By this, the added scope is reflected to the access token.这样,添加的范围就会反映到访问令牌中。

  • If you are using Service account, it is not required to remove the file.如果您使用的是服务帐户,则不需要删除该文件。

Pattern 1:模式一:

The following sample script creates new Spreadsheet to the specific folder.以下示例脚本为特定文件夹创建新电子表格。

Sample script:示例脚本:

from apiclient import discovery

destFolderId = '###'  # Please set the destination folder ID.
title = '###'  # Please set the Spreadsheet name.

drive_service = discovery.build('drive', 'v3', credentials=credentials)  # Use "credentials" of "gspread.authorize(credentials)".
file_metadata = {
    'name': title,
    'mimeType': 'application/vnd.google-apps.spreadsheet',
    'parents': [destFolderId]
}
file = drive_service.files().create(body=file_metadata).execute()
print(file)

Pattern 2:模式2:

If you want to move the existing Spreadsheet to the specific folder, please use the following script.如果要将现有电子表格移动到特定文件夹,请使用以下脚本。

Sample script:示例脚本:

from apiclient import discovery

spreadsheetId = '###'  # Please set the Spreadsheet ID.
destFolderId = '###'  # Please set the destination folder ID.

drive_service = discovery.build('drive', 'v3', credentials=credentials)  # Use "credentials" of "gspread.authorize(credentials)".
# Retrieve the existing parents to remove
file = drive_service.files().get(fileId=spreadsheetId,
                                 fields='parents').execute()
previous_parents = ",".join(file.get('parents'))
# Move the file to the new folder
file = drive_service.files().update(fileId=spreadsheetId,
                                    addParents=destFolderId,
                                    removeParents=previous_parents,
                                    fields='id, parents').execute()

References:参考:

If I misunderstood your question and this was not the direction you want, I apologize.如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

Edit:编辑:

When you want to share the folder, please use the following script.当您要共享文件夹时,请使用以下脚本。

Sample script:示例脚本:

drive_service = discovery.build('drive', 'v3', credentials=credentials)  # Use "credentials" of "gspread.authorize(credentials)".
folderId = "###"  # Please set the folder ID.
permission = {
    'type': 'user',
    'role': 'writer',
    'emailAddress': '###',  # Please set the email address of the user that you want to share.
}
res = drive_service.permissions().create(fileId=folderId, body=permission).execute()
print(res)

Reference:参考:

Here is a solution that works for me.这是一个适合我的解决方案。

It creates a new google spreadsheet within the folder on Google Drive.它会在 Google Drive 上的文件夹中创建一个新的 google 电子表格。

NOTE 1 : the folder must be shared with the Google Developer account (smth like getgooglesheets@<your-app-name>.iam.gserviceaccount.com ).注意 1 :该文件夹必须与 Google 开发者帐户共享(类似于getgooglesheets@<your-app-name>.iam.gserviceaccount.com )。 在此处输入图像描述

This email could be found in your keyfile.这个 email 可以在你的密钥文件中找到。

GOOGLE API V2谷歌 API V2

from googleapiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials

PATH_TO_KEYFILE = "./"
KEYFILE = "<appname>-<numbers>.json"  # Download from google dev account
DESTFOLDER_ID = "1lZs9O...xLW8D"  # Some folder on Google drive
TITLE = "My_New_Spread_Sheet"
EMAIL = "<new_owner_email>@gmail.com"

def share_file(...):
   """ Routine that changes rights and ownership of the file """
   ...
   return

file_metadata = {
    'title': TITLE,
    'mimeType': 'application/vnd.google-apps.spreadsheet',
    'parents': [{'id': DESTFOLDER_ID}]
}

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
keyfile = os.path.join(PATH_TO_KEYFILE, KEYFILE)
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile, scope)

drive_service = discovery.build('drive', 'v2', credentials=credentials)  # VERSION 2 GOOGLE API

response = drive_service.files().insert(body=file_metadata).execute()  # Here file is created!

print(response)  # full Google API response
print(f"🔗 LINK: https://docs.google.com/spreadsheets/d/{file['id']}/edit?usp=drivesdk") # output for convenience...
share_file(file_id=file['id'], email=EMAIL, change_ownership=True)  # Here I change ownership of the file — that is out of the scope of the question

NOTE 2 : the new file initially belongs to the developer account, not to the folder owner's account.注意 2 :新文件最初属于开发者帐户,而不属于文件夹所有者的帐户。

GOOGLE API VER 3谷歌 API 版本 3

same as above, differs in the following:同上,区别如下:

...

drive_service = discovery.build('drive', 'v3', credentials=credentials)  # VERSION 3 GOOGLE API

file_metadata = {
    'name': TITLE,  #  use 'name' property 
    'mimeType': 'application/vnd.google-apps.spreadsheet',
    'parents': [DESTFOLDER_ID]  # no dictionary inside the list
}

response = drive_service.files().create(body=file_metadata).execute() # 'create()' instead of insert() 

...

Also, the response details will slightly differ.此外,响应细节会略有不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM