RCube123
RCube123

Reputation: 213

How do I format cells in Google Sheets using Python? [AttributeError: 'Worksheet' object has no attribute 'format']

I'm building a web scraper and trying to format some data in Google Sheets via Python. In my example below, I'm able to send data stored in variables to individual cells in Google Sheets. How would I format the contents of individual cells or range of cells in Google Sheets using Python?

In my code, I'm using the gspread and BeautifulSoup libraries. To keep thing simple in my example below, let's say the data is already stored in the following variables: title, price, and rating. Then I send that data to Google Sheets and try to format the cells.

 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}})

In the code, J8, K8, and L8 refer to the cells in Google Sheets being updated. Everything runs fine up until Line 19 where I get the following error. How do I fix this? Is there something I'm missing in my code?

---------------------------------------------------------------------------
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'

On the other hand, if I bold the contents of those cells in Google Sheets before running the code, then the formatting remains after running the code. Basically, with new cell contents, the formatting is preserved from previous content. How would I update the formatting automatically using the gspread library?

Upvotes: 1

Views: 1046

Answers (1)

Marios
Marios

Reputation: 27350

Try this instead:

from gspread_formatting import *

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

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

and delete this line:

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

More information you can find here.


Also replace this:

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

with this:

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

because J,K,L are in 10th,11th,12th columns respectively.

Upvotes: 2

Related Questions