如何在Python中使用wrap_strategy来处理谷歌表格?

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

我有一个 python 代码,它使用驱动器和工作表 api 来列出文件夹内的文件。我在这个文件夹中有多个谷歌工作表,其中一些在文本之间有空格,就像图片中给出的那样。我想使用 googlesheet api 将所有单元格的文本换行更改为溢出,即 python 中的工作表对象。我可以看到有一种方法(wrap_strategy)将其设置为overflow_cell,但我不知道如何使用它。在这种情况下有人可以帮忙吗?

我可以看到应用程序脚本中的文档,但不能使用 python。

def process_file(file):
    file["name"] = file["name"] + '.' + file["id"] #prefix the file name 
    print(file["name"])
sheet = open_sheet(file['id'])
if sheet is None:
    print("Unable to open sheet: " + file['id'])
    return

实际结果将格式化此文件夹内的所有谷歌工作表,并将文本格式设置为所有单元格的溢出

python google-sheets google-sheets-api gspread
2个回答
4
投票
  • 您想要设置电子表格上工作表的换行策略。
  • 您想将sheet的所有单元格的换行策略设置为“溢出”。
  • 您想使用 gspread 来实现这一点。

从你的问题和标签,我的理解如上。

在此示例脚本中,假设将“溢出”的换行策略设置为“Sheet1”的所有单元格。 gspread使用

batch_update()
时,需要创建请求体。

示例脚本:

spreadsheetId = "###"  # Please set this
sheetName = "Sheet1"  # Please set this

client = gspread.authorize(credentials)
spreadsheet = client.open_by_key(spreadsheetId)
sheetId = ss.worksheet(sheetName)._properties['sheetId']
body = {
  "requests": [
    {
      "updateCells": {
        "range": {
          "sheetId": sheetId,
          "startRowIndex": 0,
          "startColumnIndex": 0
        },
        "rows": [
          {
            "values": [
              {
                "userEnteredFormat": {
                  "wrapStrategy": "OVERFLOW_CELL"
                }
              }
            ]
          }
        ],
        "fields": "userEnteredFormat.wrapStrategy"
      }
    }
  ]
}
res = spreadsheet.batch_update(body)

注:

  • 此示例脚本假设您已经能够使用 Sheets API 读取和写入电子表格。

参考资料:


1
投票

为什么不使用gspread格式化,这是一个简单的命令:

from gspread_formatting import *

worksheet.format("A1:D10", {"wrapStrategy": "OVERFLOW_CELL"})

就我而言,我正在寻找如何将其设置为

WRAP
,因为默认情况下它是溢出的......

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