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

时间:2016-06-28 10:45:59

标签: python google-sheets google-api google-sheets-api google-api-python-client

我一直在努力/希望解决这个问题很长一段时间。 我已经阅读了gspread的文档,但我发现有一种方法可以重命名工作表。 你们任何人都知道怎么做?我会非常欣赏它! 确实workheet.title给出了工作表的名称,但我找不到重命名实际工作表的方法。

提前谢谢!

8 个答案:

答案 0 :(得分:16)

这是我个人编码的图书馆的摘录:

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和已初始化的service,如Python QUickstart - Google Sheet API

中所述

答案 1 :(得分:3)

您的答案可以通过Python的HTTP请求解决。

链接是here

您需要通过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请求使用批量更新。

链接是here

请求的数据是

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

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

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

请注意网址中从v3到v4的更改。

如果您使用的是版本3应用程序并希望迁移,则指向here的链接

修改

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

答案 2 :(得分:1)

你可以用api v4的gspread端口实现相同的功能 - pygsheets(作者在这里)。 使用pygsheets的相应代码将是,

import pygsheets

gc = pygsheets.authorize()

# Open spreadsheet and then workseet
sh = gc.open('my new ssheet')
wks = sh.sheet1
wks.title = "new title"

答案 3 :(得分:0)

如果您使用的是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,
 },
});

答案 4 :(得分:0)

这也只能通过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();

Here,您可以在sheetProperties上找到更多信息

答案 5 :(得分:0)

对于那些使用NodeJS解决重命名的用户。只需使用batchRequest API。在sheetID中指示您正在编辑的工作表ID,并在标题字段中指示新标题。然后在字段中指出“标题”。

答案 6 :(得分: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);
    }

答案 7 :(得分:0)

尽管标题说使用 API,但问题详细信息 OP 希望使用 gspread API(而不是直接调用 Google Spreadsheets API)。

我很惊讶这个问题还没有答案。也许 gspread 在发布问题时没有这个方法,但现在 it is as simple 使用 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")

就是这样。

相关问题