簡體   English   中英

如何通過 gspread 和 python 在電子表格中創建多個工作表?

[英]How to create multiple sheets in a spreadsheet by gspread and python?

我是 Python 的新手,想練習使用 gspread 和 python 來處理電子表格。 現在我已經知道如何將 google 電子表格與 gspread 連接起來,但仍然不知道如何一次創建多個工作表。

我的期望:

  1. 一次創建多個以員工姓名命名的工作表
  2. 所以每個員工都可以使用自己的工作表

提前致謝!

employee_name = ['Jonny','Emma', ...]

從您的以下回復中,

其實我覺得2nd只是1st請求的結果,不好意思誤會了:我的想法是我可以用。 worksheet = sh,add_worksheet(title="A worksheet", rows=100, cols=20) 創建一個工作表。 但我不知道如何創建多個工作表。

我知道您想使用 gspread for python 在 Google 電子表格中添加多個工作表。 在這種情況下,下面的示例腳本怎么樣?

示例腳本:

client =  # Please use your client.

employee_names = ["Jonny", "Emma",,,] # Please set the sheet names.
spreadsheetId = "###" # Please set your spreadsheet ID.

requests = [
    {
        "addSheet": {
            "properties": {
                "title": e,
                "gridProperties": {"rowCount": 100, "columnCount": 20},
            }
        }
    }
    for e in employee_names
]
spreadsheet = client.open_by_key(spreadsheetId)
spreadsheet.batch_update({"requests": requests})
  • 在此示例腳本中,可以通過創建請求正文通過一個 API 調用插入多個工作表。 如果使用sh.add_worksheet() ,則需要使用多個 API 調用。 所以,我提出了上面的腳本。

  • 盡管我在您的顯示腳本中使用了"gridProperties": {"rowCount": 100, "columnCount": 20} ,但在這種情況下,即使"gridProperties": {"rowCount": 100, "columnCount": 20}不是使用時,工作表將作為默認行 (1000) 和列 (26) 插入。

參考:

你可以這樣做,例如:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# Set up the credentials and client
scopes = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scopes)
client = gspread.authorize(credentials)

# Open the spreadsheet
spreadsheet = client.open("My Spreadsheet")

# Get the list of employee names
employee_names = ['Jonny', 'Emma', ...]

# Iterate over the list of names and create a sheet for each of the employee
for name in employee_names:
  spreadsheet.add_worksheet(title=name, rows=100, cols=20)

這將打開工作表,獲取員工列表並遍歷列表,這樣,您就可以為每個員工創建一個新工作表,並將實際員工的姓名作為工作表標題。 希望能幫助到你

參考資料: https ://docs.gspread.org/en/v5.7.0/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM