(Feb 2017) As mentioned in another answer, Google Sheets now allows users to add Conditional Formatting directly from the user interface, whether it's on a desktop/laptop, Android or iOS devices.
Similarly, with the Google Sheets API v4 (and newer), developers can now write applications that CRUD conditional formatting rules. Check out the guide and samples pages for more details as well as the reference docs (search for {add,update,delete}ConditionalFormatRule
). The guide features this Python snippet (assuming a file ID of SHEET_ID
and SHEETS
as the API service endpoint):
myRange = {
'sheetId': 0,
'startRowIndex': 1,
'endRowIndex': 11,
'startColumnIndex': 0,
'endColumnIndex': 4,
}
reqs = [
{'addConditionalFormatRule': {
'index': 0,
'rule': {
'ranges': [ myRange ],
'booleanRule': {
'format': {'textFormat': {'foregroundColor': {'red': 0.8}}}
'condition': {
'type': 'CUSTOM_FORMULA',
'values':
[{'userEnteredValue': '=GT($D2,median($D$2:$D$11))'}]
},
},
},
}},
{'addConditionalFormatRule': {
'index': 0,
'rule': {
'ranges': [ myRange ],
'booleanRule': {
'format': {
'backgroundColor': {'red': 1, 'green': 0.4, 'blue': 0.4}
},
'condition': {
'type': 'CUSTOM_FORMULA',
'values':
[{'userEnteredValue': '=LT($D2,median($D$2:$D$11))'}]
},
},
},
}},
]
SHEETS.spreadsheets().batchUpdate(spreadsheetId=SHEET_ID,
body={'requests': reqs}).execute()
In addition to Python, Google APIs support a variety of languages, so you have options. Anyway, that code sample formats a Sheet (see image below) such that those younger than the median age are highlighted in light red while those over the median have their data colored in red font.
PUBLIC SERVICE ANNOUNCEMENT
The latest 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 (conditional formatting[!], frozen rows, cell formatting, resizing rows/columns, adding pivot tables, creating charts, etc.).
If you're new to the API & want to see slightly longer, more general "real-world" examples of using the API, I've created various videos & related blog posts:
As you can tell, the Sheets API is primarily for document-oriented functionality as described above, but to perform file-level access such as uploads & downloads, imports & exports (same as uploads & downloads but conversion to/from various formats), use the Google Drive API instead. Examples of using the Drive API:
- Exporting a Google Sheet as CSV (blog post only)
- "Poor man's plain text to PDF" converter (blog post only) (*)
(*) - TL;DR: upload plain text file to Drive, import/convert to Google Docs format, then export that Doc as PDF. Post above uses Drive API v2; this follow-up post describes migrating it to Drive API v3, and here's a video combining both "poor man's converter" posts.