如何使用Python格式化Google工作表中的单元格?[AttributeError:“工作表”对象没有属性“格式”]

2024-04-19 22:16:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个web scraper,并试图通过Python在Google表单中格式化一些数据。在我下面的示例中,我能够将存储在变量中的数据发送到Google表单中的各个单元格。如何使用Python格式化Google工作表中单个单元格或单元格范围的内容

在我的代码中,我使用了gspreadBeautifulSoup库。为了在下面的示例中保持简单,假设数据已经存储在以下变量中:titlepricerating。然后我把数据发送到谷歌表格,并尝试格式化单元格

 1   import gspread
 2
 3   # Set up access to Google Sheets, URL tail too long to display
 4   gc = gspread.authorize(GoogleCredentials.get_application_default())
 5   wb = gc.open_by_url('https://docs.google.com/spreadsheets/d/ ... ')
 6   sheet = wb.worksheet('Sheet1')
 7   
 8   # Store data into variables
 9   title = "Flash Drive"
10   price = 20.00
11   rating = 4.6
12
13   # Send data to specific cells in Google Sheets (Cells: J8, K8, L8)
14   sheet.update_cell(8, 9, title)
15   sheet.update_cell(8, 10, price)
16   sheet.update_cell(8, 11, rating)
17
18   # Make bold the contents of J8 through L8 (3 cells across)
19   sheet.format('J8:L8', {'textFormat': {'bold': True}})

在代码中,J8、K8和L8指的是正在更新的Google表单中的单元格。在Line 19出现以下错误之前,一切正常。我该如何解决这个问题?我的代码中有什么遗漏吗

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-26-477e46797660> in <module>()
     18 
     19 # Make bold the contents of J8 through L8 (3 cells across)
---> 20 sheet.format('J8:L8', {'textFormat': {'bold': True}})

AttributeError: 'Worksheet' object has no attribute 'format'

另一方面,如果我在运行代码之前在Google工作表中加粗这些单元格的内容,那么在运行代码之后,格式仍然保持不变。基本上,对于新的单元格内容,格式是从以前的内容保留下来的。如何使用gspread库自动更新格式


Tags: to数据代码表单内容titlegoogleprice
1条回答
网友
1楼 · 发布于 2024-04-19 22:16:56

请尝试以下方法:

from gspread_formatting import *

fmt = cellFormat(
    textFormat=textFormat(bold=True)
    )

format_cell_range(sheet, 'J8:L8', fmt)

并删除该行:

sheet.format('J8:L8', {'textFormat': {'bold': True}})

更多信息,请参见here


还应替换此项:

sheet.update_cell(8, 9, title)
sheet.update_cell(8, 10, price)
sheet.update_cell(8, 11, rating)

为此:

sheet.update_cell(8, 10, title)
sheet.update_cell(8, 11, price)
sheet.update_cell(8, 12, rating)

因为J、K、L分别在第10、11、12列

相关问题 更多 >