使用Gspare和Google Sheet API更改Google Sheet中的列格式 [英] Changing column format in google sheets by gspread and google sheets API

查看:28
本文介绍了使用Gspare和Google Sheet API更改Google Sheet中的列格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Gspend,我正在寻找一种适当的方法来按脚本更改列格式。我有一个带有持续时间的专栏。我想将整列的格式更改为duration。在Google UI中,我可以标记整列,然后依次单击格式、编号和设置持续时间。是否可以通过Gspend/Google Sheet API完成此操作?

编辑

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)")

推荐答案

  • 您要更改Google电子表格中列的格式。
    • 在您的情况下,在一列中有持续时间的值。您想要更改持续时间的格式。
  • 您希望通过使用带有Python的Gspare来实现这一点。
  • 您已经能够使用带有Gspend的Sheets API来获取和放置电子表格的值。

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

修改点:

  • 为了更改列的格式,使用了spadsheets.BatchUpdate in Sheets API的方法和spadsheets.BatchUpdate方法的RepeatCellRequest.在Gspend,spadsheets.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)
  • 作为测试用例,当A列的第1行(单元格A1)的持续时间为1:23:45时,当上面的脚本(格式模式为[m]:s)。运行时,1:23:45变为83:45
    • 顺便说一下,1:23:45作为时长的格式为[h]:mm:ss
  • 如果格式模式为[s],则1:23:45变为5025

注意:

  • 当您使用此脚本时,我建议使用示例电子表格。因为脚本更改了格式。
  • 在上述修改后的脚本中,电子表格名称sys.argv[1]中第一个页签的"A"列的持续时间格式改为[m]:s
  • 这是一个简单的示例脚本。因此,请根据您的实际情况进行修改。特别是,请根据您的实际情况修改格式模式。因为我不太清楚你的实际情况。

引用:

这篇关于使用Gspare和Google Sheet API更改Google Sheet中的列格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆