我正在構建一個網絡抓取工具并嘗試通過 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 列。
添加回答
舉報
0/150
提交
取消