如何使用Python API在Google表格电子表格中重命名(工作)表?

30

我已经试图解决/寻找解决这个问题已经有一段时间了。 我已阅读过gspread的文档,但未找到重命名工作表的方法。 你们当中有人知道吗?我会非常感激! 确实有worksheet.title可以获取工作表的名称,但我找不到重命名实际表格的方法。

提前感谢您!


你可以借助Google Apps Script实现这一点。你可以使用rename(newName)来重命名文档。 var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.rename("This is the new name"); 如果你想将当前活动工作表重命名为给定的新名称,你可以调用renameActiveSheet(newName)。 // 下面的代码将把活动工作表重命名为“Hello world” SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet("Hello world"); 更多信息请查看文档 - KENdi
1
@KENdi 但是,如何在Python中实现这个呢? - Ilden Gemil
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Christophe
@Christophe 我认为在Google Sheet API文档中,最难理解的部分是关于UpdateSheetPropertiesRequestfields参数,它告诉API请求期间应该编辑什么内容。在下面的示例中,sheetId仅用于更新标题。我不知道如果将fields参数更改为“sheetId”,那么该请求是否能够更新sheetId(例如)。 - Mattia Galati
你能否将工作表数据复制到另一个名称不同的工作表中并删除原始数据?你正在处理的文件有多大? - rassa45
之前可以用 worksheet.update_title(title),但现在不能用了。 - manas
8个回答

35

这是我个人编写的一个库的提取:

def _batch(self, requests):
    body = {
        'requests': requests
    }
    return self._service.spreadsheets().batchUpdate(spreadsheetId=self.spreadsheetId, body=body).execute()

def renameSheet(self, sheetId, newName):
    return self._batch({
        "updateSheetProperties": {
            "properties": {
                "sheetId": sheetId,
                "title": newName,
            },
            "fields": "title",
        }
    })

我认为只要稍加努力,你就可以将其实现到你的代码中,并获得你想要的结果。 为了进行batchUpdate调用,你需要获取spreadsheetId以及根据Python Quickstart - Google Sheet API中所述初始化的service


1
这个答案刚刚超级简化了“FieldMasks”。为什么它必须如此复杂,但是很好的答案。 - Antony
1
我同意你的观点,我能想到的唯一答案是谷歌采用这种方法是为了抽象出任何特征并支持几乎任何类型的操作,只需使用一个方法。 - Mattia Galati
1
提示:如果您想重命名第一个工作表,但没有sheetId,则可以省略sheetId属性。 - Asaf Shveki
如果您想要使用batchupdate UpdateSheetProperties API调用一次性修改多个属性,请查看JSON请求结构:添加您的“properties”,并在“fields”字符串内容中逗号分隔它们的名称。FieldMasks格式很复杂,但我在这里找到了一个很好的解释。 - abu

5
尽管标题中写着“使用API”,但问题的详细信息中,OP想要使用gspread API(而不是直接调用Google Spreadsheets API)。
我很惊讶目前还没有答案。也许当问题发布时,gspread还没有这个方法,但现在使用update_title方法就像简单的操作一样。
import gspread

# authenticate:
gc = gspread.service_account()
# choose a gspread method to open your spreadsheet and your worksheet:
wsh = gc.open_by_key(spreadsheetId).worksheet("old_WorkSheetName")
# update your worksheet name:
wsh.update_title("new_WorksheetName")

就是这样。


这是最佳答案。 - yane

4

您可以通过Python发送HTTP请求来解决您的问题。

链接在这里

您需要通过HTTP发送一些工作表的元数据。

例如,使用Python获取工作表的ID,并发送以下信息:

<entry>
  <id>
    https://spreadsheets.google.com/feeds/worksheets/key/private/full/worksheetId
  </id>
  <updated>2007-07-30T18:51:30.666Z</updated>
  <category scheme="http://schemas.google.com/spreadsheets/2006"
    term="http://schemas.google.com/spreadsheets/2006#worksheet"/>
  <title type="text">Income</title>
  <content type="text">Expenses</content>
  <link rel="http://schemas.google.com/spreadsheets/2006#listfeed"
    type="application/atom+xml" href="https://spreadsheets.google.com/feeds/list/key/worksheetId/private/full"/>
  <link rel="http://schemas.google.com/spreadsheets/2006#cellsfeed"
    type="application/atom+xml" href="https://spreadsheets.google.com/feeds/cells/key/worksheetId/private/full"/>
  <link rel="self" type="application/atom+xml"
    href="https://spreadsheets.google.com/feeds/worksheets/key/private/full/worksheetId"/>
  <link rel="edit" type="application/atom+xml"
    href="https://spreadsheets.google.com/feeds/worksheets/key/private/full/worksheetId/version"/>
  <gs:rowCount>45</gs:rowCount>
  <gs:colCount>15</gs:colCount>
</entry>

该网站还拥有Java和.NET解决方案。(这是针对旧版本3的)

对于较新的版本,您也可以使用来自Python的POST http请求进行批量更新。

链接在这里

请求的数据为:

{
  "requests": [{
      "updateSpreadsheetProperties": {
          "properties": {"title": "My New Title"},
          "fields": "title"
        }
    }]
}

需要通过POST发送到https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId:batchUpdate

在这两个请求中,将URL中的spreadsheetId替换为您正在编辑的Google表格的ID。

请注意URL中从v3更改为v4。

如果您正在使用版本3应用程序并希望迁移,请单击此处

编辑

一位评论者指出第二个请求不会更改工作表的名称。我添加的链接显示了更改工作表的复杂属性的方法,我将很快更新我的答案。


1
请注意,您发布的请求涉及更改“电子表格”(因此您的请求将重命名整个电子表格),但用户明确要求如何重命名“工作表”。 - Mattia Galati
啊,我明白第二个请求并没有这样做,但是我链接的页面展示了更复杂的电子表格属性,也可以进行编辑。然而,虽然已经被弃用但仍然可用的API请求应该也能够更改工作表的名称,因为原帖作者可以从他们的代码中获取工作表的ID(他们提到了可以获取标题,所以也可以获取ID)。 - rassa45
1
只需添加特定的sheetID即可更新特定工作表,例如{"requests": [{"updateSheetProperties": {"properties": {"sheetId": "My Sheet ID", "title": "My New Title"}, "fields": "title"}}]};http地址保持不变。 - Luke

3
您可以使用 api v4 的 gspread 端口 pygsheets 来实现相同的功能:pygsheets(作者在这里)。
使用 pygsheets 的相应代码如下:
import pygsheets

gc = pygsheets.authorize()

# open spreadsheet and then worksheet
sh = gc.open('my new spreadsheet')
wks = sh.sheet1
wks.title = 'new title'

1
这也可以仅使用Google API方法来实现。
以下是一种无需json的解决方案。
sheetsService = getSheetsService();
// create a SheetProperty object and put there all your parameters (new title, sheet id, something else)
SheetProperties title = new SheetProperties().setSheetId(0).setTitle("Main");
// make a request with this properties
UpdateSheetPropertiesRequest rename = new UpdateSheetPropertiesRequest().setProperties(title);
// set fields you want to update
rename.setFields("title");
// as requestBody.setRequests gets a list, you need to compose an list from your request
List<Request> requests = new ArrayList<>();
// convert to Request
Request request = new Request().setUpdateSheetProperties(rename);
requests.add(request);
BatchUpdateSpreadsheetRequest requestBody = new BatchUpdateSpreadsheetRequest();
requestBody.setRequests(requests);
// now you can execute batchUpdate with your sheetsService and SHEET_ID
sheetsService.spreadsheets().batchUpdate(SHEET_ID, requestBody).execute();

这里可以找到有关sheetProperties的更多信息。


确实,这是使用Java的完美解决方案。运行得非常好。谢谢! - Gaurav Khandelwal

1
如果您正在使用Node,以下是对我有用的内容:
import {google} from 'googleapis';

const auth = new google.auth.OAuth2(...)

const sheetsService = google.sheets({version: 'v4', auth})

const requests = [
 {
  updateSheetProperties: {
   properties: {
    sheetId: 'id-of-the-sheet-that-you-want-to-rename',
    title: 'new-title',
   },
   fields: 'title'
   }
  }
];

sheetsService.spreadsheets.batchUpdate({
 spreadsheetId: 'some-spreasheet-id',
 requestBody: {
  requests,
 },
});

0

使用PHP

    public function updateSheetTitle(string $fileId, string $title, ?int $sheetId = NULL): void
    {
        if (!$sheetId) {
            // rename first sheet
            $file = $this->get($fileId);
            if (!$file->getSheets()) {
                throw new NoSheetsException();
            }
            $sheetId = $file->getSheets()[0]->getProperties()->getSheetId();
        }
        $titleProp = new Google_Service_Sheets_SheetProperties();
        $titleProp->setSheetId($sheetId);
        $titleProp->setTitle($title);

        $renameReq = new Google_Service_Sheets_UpdateSheetPropertiesRequest();
        $renameReq->setProperties($titleProp);
        $renameReq->setFields('title');

        $request = new Google_Service_Sheets_Request();
        $request->setUpdateSheetProperties($renameReq);

        $batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
        $batchUpdateRequest->setRequests([$request]);

        $this->spreadsheets->batchUpdate($fileId, $batchUpdateRequest);
    }

0
对于那些使用NodeJS解决此重命名问题的人,请使用batchRequest API。在sheetID中指示您正在编辑的工作表ID和标题字段中的新标题。然后在字段中指示“title”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接