在google工作表API V4中使用python设置特定单元格的格式



我尝试在谷歌电子表格中将一些单元格格式化为日期格式。

单元格上的数据看起来是这样的:2021年9月11日
我试着让它看起来是这样:<strong]2021年11月>
或者至少用日期格式格式化单元格。

我使用batchUpdate((更新单元格:
request = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute()

我尝试过的:

  • 两个updateCellsrepeatCell都无效
  • 将值添加到单元格后,在AND之前进行格式化
  • 通过更改rowncoln
  • 其他日期格式,如dd-mm-yymm yyyy
  • 还阅读了许多谷歌文档并观看了他们的视频

更新单元格正文

body = {
"requests": [
{
'updateCells': {
'range': {
'sheetId': sheet_id,
'startRowIndex': rown-1,
'endRowIndex': rown,
'startColumnIndex': coln,
'endColumnIndex': coln
},
'rows': {'values': [{'userEnteredFormat': {'numberFormat': {'type': "DATE", 'pattern': "mm/yyyy"}}}]},
'fields': 'userEnteredFormat.numberFormat'
}
}
]
}

repeatCell主体

body = {
"requests": [
{
"repeatCell": {
"range": {
"sheetId": sheet_id,
"startRowIndex": rown-1,
"endRowIndex": rown,
"startColumnIndex": coln,
"endColumnIndex": coln
},
"cell": {
"userEnteredFormat": {
"numberFormat": {
"type": "DATE",
"pattern": "mm/yyyy"
}
}
},
"fields": "userEnteredFormat.numberFormat"
}
}
]
}

欢迎任何提示、技巧或想法!

我认为在您的请求体中,问题的原因可能是'startColumnIndex': coln,'endColumnIndex': coln的值相同。例如,如何修改您的请求体如下?

对于updateCells body

body = {
"requests": [
{
'updateCells': {
'range': {
'sheetId': sheet_id,
'startRowIndex': rown-1,
'endRowIndex': rown,
'startColumnIndex': coln-1, # Modified
'endColumnIndex': coln
},
'rows': {'values': [{'userEnteredFormat': {'numberFormat': {'type': "DATE", 'pattern': "mm/yyyy"}}}]},
'fields': 'userEnteredFormat.numberFormat'
}
}
]
}

对于repeatCell body

body = {
"requests": [
{
"repeatCell": {
"range": {
"sheetId": sheet_id,
"startRowIndex": rown-1,
"endRowIndex": rown,
"startColumnIndex": coln-1, # Modified
"endColumnIndex": coln
},
"cell": {
"userEnteredFormat": {
"numberFormat": {
"type": "DATE",
"pattern": "mm/yyyy"
}
}
},
"fields": "userEnteredFormat.numberFormat"
}
}
]
}

注:

  • 在上述修改后的请求体中,例如,当rowncoln的值分别为11时,小区的编号格式为"0";A1〃;被修改
  • 在这个修改后的脚本中,它假设单元格中09/11/2021的值是日期对象。请小心

参考:

  • 更新CellsRequest
  • RepeatCellRequest

最新更新