如何使用 Python 格式化 Google 表格中的单元格?[属性错误:'Worksheet'对象没有属性"格式"]



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

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

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 Sheets中的单元格。在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 Sheets中这些单元格的内容加粗,那么在运行代码之后,格式将保持不变。基本上,对于新的单元格内容,格式将从以前的内容中保留下来。如何使用gspread库自动更新格式?

试试这个:

from gspread_formatting import *
fmt = cellFormat(
textFormat=textFormat(bold=True)
)
format_cell_range(sheet, 'J8:L8', fmt)

并删除此行:

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

您可以在这里找到更多信息。


也替换此:

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列。

最新更新