在Gspread中,我如何删除所有工作表并重新开始?

发布于 2025-02-01 14:21:25 字数 1733 浏览 3 评论 0 原文

对于我的用例,我必须动态生成一些报告,因此我认为从头开始创建报告会更容易。每次用户请求报告时,我都想首先清除整个电子表格,然后从新的数据库查询中生成工作表。我试图循环浏览每个工作表并删除每个工作表,但无法删除最后一个。这是我的代码:

import gspread
gc = gspread.service_account()
sh = gc.open("My Google Sheet")
for s in sh.worksheets():
    sh.del_worksheet(s)

这是我遇到的错误:

---------------------------------------------------------------------------
APIError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17768/423772843.py in <module>
      1 sh = gc.open(report_name)
      2 for s in sh.worksheets():
----> 3     sh.del_worksheet(s)

~\anaconda3\envs\analytics\lib\site-packages\gspread\spreadsheet.py in del_worksheet(self, worksheet)
    436         body = {"requests": [{"deleteSheet": {"sheetId": worksheet.id}}]}
    437 
--> 438         return self.batch_update(body)
    439 
    440     def reorder_worksheets(self, worksheets_in_desired_order):

~\anaconda3\envs\analytics\lib\site-packages\gspread\spreadsheet.py in batch_update(self, body)
    128         .. versionadded:: 3.0
    129         """
--> 130         r = self.client.request(
    131             "post", SPREADSHEET_BATCH_UPDATE_URL % self.id, json=body
    132         )

~\anaconda3\envs\analytics\lib\site-packages\gspread\client.py in request(self, method, endpoint, params, data, json, files, headers)
     78             return response
     79         else:
---> 80             raise APIError(response)
     81 
     82     def list_spreadsheet_files(self, title=None, folder_id=None):

APIError: {'code': 400, 'message': "Invalid requests[0].deleteSheet: You can't remove all the sheets in a document.", 'status': 'INVALID_ARGUMENT'}

For my use case, I have to generate some reports dynamically, so I thought it would be easier to just create the report from scratch. Every time the user requests the report, I would like to first clear the entire spreadsheet and then generate the worksheets from fresh database queries. I tried to loop through every worksheet and delete each one, but I couldn't delete the last one. Here is my code:

import gspread
gc = gspread.service_account()
sh = gc.open("My Google Sheet")
for s in sh.worksheets():
    sh.del_worksheet(s)

Here is the error I'm getting:

---------------------------------------------------------------------------
APIError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17768/423772843.py in <module>
      1 sh = gc.open(report_name)
      2 for s in sh.worksheets():
----> 3     sh.del_worksheet(s)

~\anaconda3\envs\analytics\lib\site-packages\gspread\spreadsheet.py in del_worksheet(self, worksheet)
    436         body = {"requests": [{"deleteSheet": {"sheetId": worksheet.id}}]}
    437 
--> 438         return self.batch_update(body)
    439 
    440     def reorder_worksheets(self, worksheets_in_desired_order):

~\anaconda3\envs\analytics\lib\site-packages\gspread\spreadsheet.py in batch_update(self, body)
    128         .. versionadded:: 3.0
    129         """
--> 130         r = self.client.request(
    131             "post", SPREADSHEET_BATCH_UPDATE_URL % self.id, json=body
    132         )

~\anaconda3\envs\analytics\lib\site-packages\gspread\client.py in request(self, method, endpoint, params, data, json, files, headers)
     78             return response
     79         else:
---> 80             raise APIError(response)
     81 
     82     def list_spreadsheet_files(self, title=None, folder_id=None):

APIError: {'code': 400, 'message': "Invalid requests[0].deleteSheet: You can't remove all the sheets in a document.", 'status': 'INVALID_ARGUMENT'}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无尽的现实 2025-02-08 14:21:25

我认为您的问题的原因是由于Google电子表格当前规范不能删除所有床单。这已经在评论和现有答案中提到。

关于您的脚本,当我看到Gsperad的脚本时,看来 sh.del_worksheet(s)是通过使用一个配额API来运行的。 在循环中使用,板API连续使用。当床单数量很大时,我担心可能会出现错误。

因此,在此答案中,我想提出一个示例脚本,以通过2个API呼叫实现您的目标。

模式1:

在此模式中,清除了第一张纸,除了第一张纸外,其他纸张被清除。

worksheets = sh.worksheets()
reqs = [{"repeatCell": {"range": {"sheetId": s.id}, "fields": "*"}} if i == 0 else {"deleteSheet": {"sheetId": s.id}} for i, s in enumerate(worksheets)]
sh.batch_update({"requests": reqs})

模式2:

在此模式下,插入了新的纸张,并删除所有其他纸张。

worksheets = sh.worksheets()
reqs = [{"addSheet": {"properties": {"index": 0}}}] + [{"deleteSheet": {"sheetId": s.id}} for s in worksheets]
sh.batch_update({"requests": reqs})

注意:

  • 在这些示例脚本中, sh.worksheets()使用一个API调用。并且, sh.batch_update({“ requests”:reqs})使用一个API调用。

参考:

I think that the reason for your issue is due to that all sheets cannot be removed by the current specification at Google Spreadsheet. This has already been mentioned in the comments and the existing answer.

About your script, when I saw the script of gsperad, it seems that sh.del_worksheet(s) is run by using one quota of Sheets API. Ref By this, when sh.del_worksheet(s) is used in a loop, Sheets API is continuously used. When the number of sheets is large, I'm worried that an error might occur.

So, in this answer, I would like to propose a sample script for achieving your goal with 2 API calls.

Pattern 1:

In this pattern, 1st sheet is cleared and other sheets except for the 1st sheet are removed.

worksheets = sh.worksheets()
reqs = [{"repeatCell": {"range": {"sheetId": s.id}, "fields": "*"}} if i == 0 else {"deleteSheet": {"sheetId": s.id}} for i, s in enumerate(worksheets)]
sh.batch_update({"requests": reqs})

Pattern 2:

In this pattern, a new sheet is inserted and all other sheets are removed.

worksheets = sh.worksheets()
reqs = [{"addSheet": {"properties": {"index": 0}}}] + [{"deleteSheet": {"sheetId": s.id}} for s in worksheets]
sh.batch_update({"requests": reqs})

Note:

  • In these sample scripts, sh.worksheets() uses one API call. And, sh.batch_update({"requests": reqs}) uses one API call.

Reference:

吾家有女初长成 2025-02-08 14:21:25

您无法删除最后的表格,但是解决此问题的一种方法是添加新的空白表,然后删除要删除的所有表,构建报告,最后删除空白表。

You can't delete the last sheet, but one way to work around this is to add a new blank sheet, and then delete all the sheets you want to delete, build your report, and at the end delete the blank sheet.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文