Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a Google Sheets spreadsheet cell with the API?

My application generates a table of data and creates a new spreadsheet document in a user's Google Drive. How can I add formatting (color, font-weight, width, etc.) to individual cells? I can't seem to find any documentation, much less how I could implement this through the google-api-ruby-client.

Most of my findings date back to Google API mailing lists that state it isn't supported.
However, I found that another application accomplishes my desired result. An example of "Smartsheet" exporting a document to Google Drive:

From Smartsheet.com:

At Smartsheet.com

And the resulting sheet in my Google Drive:

In my Google Drive

like image 800
tbeseda Avatar asked Dec 03 '12 23:12

tbeseda


1 Answers

(Feb 2017) As of Google I/O 2016, developers no longer need to export to Excel nor create a new Sheet w/the desired formatting, so the other answers are now dated. You can now format cells using the Google Sheets API. Here's a short Python example that bolds the 1st row (assuming the file ID is SHEET_ID and SHEETS is the API service endpoint):

DATA = {'requests': [
    {'repeatCell': {
        'range': {'endRowIndex': 1},
        'cell':  {'userEnteredFormat': {'textFormat': {'bold': True}}},
        'fields': 'userEnteredFormat.textFormat.bold',
    }}
]}

SHEETS.spreadsheets().batchUpdate(
        spreadsheetId=SHEET_ID, body=DATA).execute()

I also made a developer video on this subject if that helps (see below). BTW, you can do the same in Ruby (see its API quickstart sample) or any other language supported by the Google APIs Client Libraries.

The Sheets API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (frozen rows, cell formatting[!], resizing rows/columns, adding pivot tables, creating charts, etc.). If you're new to the API, I've created a few videos with somewhat more "real-world" examples:

  • Migrating SQL data to a Sheet plus code deep dive post
  • Formatting text using the Sheets API plus code deep dive post
  • Generating slides from spreadsheet data plus code deep dive post

To see what else you can do with Google Sheets via its REST API or Google Apps Script, check out my other videos. As you can tell, the Sheets API is primarily for document-oriented functionality as described above, but to perform file-level access such as import/export, copy, move, rename, etc., use the Google Drive API instead.

like image 81
wescpy Avatar answered Oct 05 '22 09:10

wescpy