通过 gspread 和 Google Sheets API 更改 Google Sheets 中的列格式

2024-02-29

我正在使用 gspread,并且正在寻找一种通过脚本更改列格式的正确方法。我有一个包含持续时间的专栏。我想将整个列的格式更改为duration。在 Google UI 中,我可以标记整个列,然后单击格式,然后单击编号并设置duration。是否可以通过 gspread/google Sheets API 来做到这一点?

EDIT

client = gspread.authorize(credentials)

try:
  sheet = client.open(sys.argv[1]).sheet1
except (gspread.SpreadsheetNotFound, IndexError):
  print("Spreadsheet not found")
  sys.exit()

try:
  tags = sheet.col_values(13)
  tags.remove('Tags')
  unique_tags = list(dict.fromkeys(tags))
except ValueError:
  print("Your spreadsheet cannot be modified and should contain original 
  columns from toggle reports.")
  sys.exit()


START_INDEX = 7
sheet.update_cell(6, 15, "SUM")
for tag in unique_tags:
  sheet.update_cell(START_INDEX, 15, tag)
  sheet.update_cell(START_INDEX, 16, "=SUMIF(M2:M; " + '"' + tag + '"' + "; 
  L2:L)")
  START_INDEX += 1

sheet.update_cell(6, 16, "=SUM(P7:P15)")

  • You want to change the format of a column on Google Spreadsheet.
    • 在您的情况下,列中有持续时间的值。您想要更改持续时间的格式。
  • 您希望使用 gspread 和 python 来实现此目的。
  • 您已经能够使用 Sheets API 和 gspread 获取和输入电子表格的值。

如果我的理解是正确的,这个答案怎么样?请将此视为几个可能答案之一。

修改点:

  • 为了更改列的格式,使用Sheets API中的spreadsheets.batchUpdate方法和spreadsheets.batchUpdate方法的“RepeatCellRequest”。在gspread中,spreadsheets.batchUpdate的方法可以用作batch_update(body).

修改后的脚本:

在此修改中,使用了问题中脚本的顶部部分。

try:
    spreadsheet = client.open(sys.argv[1])  # Modified
    sheet = spreadsheet.sheet1  # Added
except (gspread.SpreadsheetNotFound, IndexError):
    print("Spreadsheet not found")
    sys.exit()

# I added below script.
requests = [{
    "repeatCell": {
        "range": {
            "startColumnIndex": 0,
            "endColumnIndex": 1,
            "sheetId": sheet._properties['sheetId']
        },
        "cell": {
            "userEnteredFormat": {
                "numberFormat": {
                    "type": "TIME",
                    "pattern": "[m]:s"
                }
            }
        },
        "fields": "userEnteredFormat.numberFormat"
    }
}]
body = {
    'requests': requests
}
res = spreadsheet.batch_update(body)
print(res)
  • As a test case, when the row 1 of the column "A" (the cell "A1") has 1:23:45 as the time duration, when above script (the format pattern is [m]:s.) is run, 1:23:45 becomes 83:45.
    • 顺便说一句,格式模式1:23:45因为持续时间是[h]:mm:ss.
  • 如果格式模式是[s], 1:23:45变成5025.

Note:

  • 当您使用此脚本时,我建议使用示例电子表格。因为格式是被脚本改变的。
  • 在上面修改的脚本中,电子表格名称中第一个选项卡上的列“A”的持续时间格式sys.argv[1]更改为[m]:s.
  • 这是一个简单的示例脚本。所以请根据您的实际情况进行修改。特别是,请根据您的实际情况修改格式模式。因为我不确定你的实际情况。

参考:

  • 批量更新(主体) https://gspread.readthedocs.io/en/latest/api.html?highlight=batch_update#gspread.models.Spreadsheet.batch_update
  • 方法:spreadsheets.batchUpdate https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate
  • 重复单元格请求 https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#repeatcellrequest
  • 日期和数字格式 https://developers.google.com/sheets/api/guides/formats

  • 对于持续时间的模式,官方文档是这样说的。

    • [h+]:一段时间内经过的小时数。字母数表示最小位数(添加前导 0)。
    • [m+]:一段时间内经过的分钟数。字母数表示最小位数(添加前导 0)。
    • [s+]:一段时间内经过的秒数。字母数表示最小位数(添加前导 0)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 gspread 和 Google Sheets API 更改 Google Sheets 中的列格式 的相关文章

随机推荐