如何使用 gspread 将工作表复制到现有工作表?

问题描述 投票:0回答:1

在 Google Sheets 中,可以手动将给定工作表中的工作表复制到另一工作表;我想用

gspread
以编程方式执行此操作。例如,如果我的驱动器中有 2 张工作表 - spreadsheet_1spreadsheet_2 - 我想将工作表 ws_1spreadsheet_1 复制到 spreadsheet_2

我通读了一些 gspread 文档,发现

Worksheet
对象有一个名为
copy_to
的方法,可以将给定的工作表复制到另一张工作表。我尝试在以下代码中使用它。

# import, authenticate, make gspread client
from google.colab import auth
auth.authenticate_user()

import gspread
from google.auth import default

creds, _ = default()
gc = gspread.authorize(creds)

# access worksheet ws_1 from sheet spreadsheet_1
sh_1 = gc.open('spreadsheet_1')
ws = sh_1.worksheet('ws_1')

# copy the worksheet to spreadsheet_2
sh_2 = gc.open('spreadsheet_2')
ws.copy_to(sh_2.id) # reference spreadsheet_2 with its id

错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-9-b388ead7ce3a> in <cell line: 5>()
      3 
      4 sh_2 = gc.open('spreadsheet_2')
----> 5 ws.copy_to(sh_2.id)

AttributeError: 'Worksheet' object has no attribute 'copy_to'

但是根据我收到的属性错误,

Worksheet
实际上没有这样的方法。我尝试进一步查看文档,但确实不清楚如何完成此任务。

python gspread
1个回答
0
投票

升级
gspread
版本以使用 Worksheet.copy_to

Google Colab 中的每个笔记本都预装了 gspread 3.4.2。

  • 在单元格中运行
    !pip list -v | grep gspread
    以查看版本和位置

根据 gpsread 存储库中的 Release History,3.6.0 版本添加了

Worksheet.copy_to
。因此,必须更新 gspread 版本才能使用该方法。

  • 更新到最新版本:
    !pip install --upgrade gspread
  • 安装特定版本(例如3.6.0):
    !pip install gspread==3.6.0

升级的替代方案

如果出于某种原因不想升级到具有该方法的版本,可以使用以下函数代替。

def copy_to(gs_client, sheet_id, spreadsheet_id, destination_spreadsheet_id):
    """
    Directly calls `spreadsheets.sheets.copyTo
    <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.sheets/copyTo>`_.
    """

    url = f"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}/sheets/{sheet_id}:copyTo"

    body = {"destinationSpreadsheetId": destination_spreadsheet_id}
    r = gs_client.request("post", url, json=body)
    return r.json()

这实现了与

Worksheet.copy_to
相同的最终结果。这基本上就是
Worksheet.copy_to
的工作原理;我从模块的源代码中获取它。

© www.soinside.com 2019 - 2024. All rights reserved.