为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Python 格式化 Google 表格中的单元格?

如何使用 Python 格式化 Google 表格中的单元格?

狐的传说 2023-05-09 10:06:04
我正在构建一个网络抓取工具并尝试通过 Python 格式化 Google 表格中的一些数据。在下面的示例中,我能够将存储在变量中的数据发送到 Google 表格中的各个单元格。我如何使用 Python 格式化 Google 表格中单个单元格或单元格范围的内容?在我的代码中,我使用了gspread和BeautifulSoup库。为了在下面的示例中保持简单,假设数据已存储在以下变量中:title、price和rating。然后我将该数据发送到 Google 表格并尝试格式化单元格。 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.0011   rating = 4.61213   # 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)1718   # 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?
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

试试这个:


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


查看完整回答
反对 回复 2023-05-09
  • 1 回答
  • 0 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信