Gspread-如何在不超过配额限制的情况下一次格式化多个单元格



本质上,我试图通过更改每个单元格的颜色将图像打印到工作表上。当涉及到小图像时,它可以做得很好。然而,我将要导入的大多数图像都超过100x100。这不仅非常慢,而且我不能在不超过配额限制的情况下完成。

我不认为使用format()1000+次是非常优化的,有没有一种方法可以设置我的格式,然后";"推";在不调用API太多次的情况下将其添加到工作表中?

for row in rows:
for column in columns:
color = (image.get_at((column, row)))
address = utils.rowcol_to_a1(row+1, column+1)
#the part where it formats the cell
sheet2.format(str(address), {"backgroundColor": {'red': color[0]/255, 'green': color[1]/255, 'blue': color[2]/255}})

image.get_at()来自另一个模块,它只是得到一个像素的颜色。

对图像中的每个单个像素调用CCD_ 3。

我知道我可以使用time.sleep()来等待配额重置,但按照这种速度,导入任何合适大小的图像都需要很长时间。

我相信您的目标如下。

  • 您希望降低脚本的处理成本
  • 您希望使用python的gspread来实现这一点。
    • 根据您的演示脚本,我认为您可能会使用gspread

在您的情况下,使用batch_update怎么样?当使用batch_update时,可以通过一个API调用来实现请求。当您的脚本被修改时,下面的修改如何?

修改的脚本:

image = ### # Please declare image.
spreadsheetId = "###" # Please set your Spreadsheet ID.
spreadsheet = client.open_by_key(spreadsheetId)
sheet2 = spreadsheet.worksheet("Sheet1") # Please set your sheet name.
rows = [0, 1, 2, 3,,,] # Please set values of rows.
columns = [0, 1, 2, 3,,,] # Please set values of columns.

rowValues = []
for row in rows:
colValues = []
for column in columns:
color = (image.get_at((column, row))) # I used your script here.
colValues.append({"userEnteredFormat": {"backgroundColorStyle": {"rgbColor": {"red": color[0] / 255,"green": color[1] / 255,"blue": color[2] / 255}}}})
rowValues.append({"values": colValues})
requests = {"requests": [{"updateCells": {"rows": rowValues,"range": {"sheetId": sheet2.id,"startRowIndex": rows[0],"endRowIndex": rows[-1] + 1,"startColumnIndex": columns[0],"endColumnIndex": columns[-1] + 1},"fields": "userEnteredFormat.backgroundColorStyle"}}]}
spreadsheet.batch_update(requests)
  • 运行此脚本时,会创建一个UpdateCellsRequest请求,并使用Sheets API的batchUpdate方法进行请求。我以为这样,你的问题也许就能解决了

注意:

  • 在这个示例脚本中,它假设rowscolumns的值是由连续数创建的类似于[0, 1, 2, 3,,,]的数组。

  • 不幸的是,我不知道你的实际情况。所以,我不能知道rowscolumns的值。那么,当上面的脚本不起作用时,你能提供更多信息吗?例如,你能提供样本值吗?通过此操作,我想修改脚本。

参考文献:

  • batch_update(正文(
  • 方法:spreadsheets.batchUpdate
  • 更新单元格请求

最新更新