條件式格式可讓您設定儲存格格式,讓儲存格外觀根據儲存格內含的值或其他儲存格中的值,動態變更。條件式格式有許多可能的應用方式,包括:
- 醒目顯示超過特定門檻的儲存格 (例如,所有超過 $2,000 美元的交易都以粗體顯示)。
- 設定儲存格格式,讓儲存格顏色會隨其值而變化 (例如,當金額超過 $2,000 時,就會套用更鮮豔的紅色背景)。
- 根據其他儲存格的內容動態設定儲存格的格式 (例如,醒目顯示「time on market」欄位大於 90 天的房屋地址)。
甚至可以根據儲存格值和其他儲存格值設定儲存格格式。舉例來說,您可以根據儲存格值與該範圍中位數值的比較結果,設定儲存格範圍的格式:
圖 1. 格式化方式,醒目顯示高於或低於中位年齡的值。
在這個範例中,每個資料列中的儲存格會根據 age
資料欄中的值與所有年齡的中位數值比較,進行格式設定。年齡高於中位數的資料列會顯示紅色文字,而低於中位數的資料列則會顯示紅色背景。其中兩列的 age
值與平均年齡 (48 歲) 相符,且這些儲存格沒有任何特殊格式。(如需建立此條件式格式的原始程式碼,請參閱下方的範例)。
條件式格式設定規則
條件式格式設定會使用格式設定規則表示。每個試算表都會儲存這些規則的清單,並按照清單中的順序套用這些規則。您可以使用 Google Sheets API 新增、更新及刪除這些格式規則。
每個規則都會指定目標範圍、規則類型、觸發規則的條件,以及要套用的任何格式。
目標範圍:可以是單一儲存格、儲存格範圍或多個範圍。
規則類型:規則分為兩種類型:
每種規則類型都會評估不同的條件,並可套用不同的格式,詳情請參閱下文。
布林值規則
BooleanRule
會根據評估為 true
或 false
的 BooleanCondition
,定義是否要套用特定格式。布林值規則的格式如下:
{
"condition": {
object(BooleanCondition)
},
"format": {
object(CellFormat)
},
}
條件可以使用內建的 ConditionType
,也可以使用自訂公式進行更複雜的評估。
內建類型可讓您根據數值門檻、文字比較或儲存格是否已填入資料來套用格式。例如,NUMBER_GREATER
表示儲存格值必須大於條件值。系統一律會根據目標儲存格評估規則。
自訂公式是一種特殊條件類型,可讓您根據任意運算式套用格式,而且不只限於評估目標儲存格,也能評估任何儲存格。條件的公式必須評估為 true
。
如要定義布林值規則套用的格式,請使用 CellFormat
類型的子集來定義:
- 儲存格中的文字是否為粗體、斜體或刪除線。
- 儲存格中的文字顏色。
- 儲存格的背景顏色。
漸層規則
GradientRule
會定義一系列顏色,這些顏色會對應至一系列值。漸層規則的格式如下:
{
"minpoint": {
object(InterpolationPoint)
},
"midpoint": {
object(InterpolationPoint)
},
"maxpoint": {
object(InterpolationPoint)
},
}
每個 InterpolationPoint
都會定義顏色及其對應的值。一組三個點會定義色彩漸層。
管理條件式格式設定規則
如要建立、修改或刪除條件式格式規則,請使用 spreadsheets.batchUpdate
方法搭配適當的要求類型:
使用
AddConditionalFormatRuleRequest
在指定索引的清單中新增規則。使用
UpdateConditionalFormatRuleRequest
在指定索引處取代或重新排序清單中的規則。使用
DeleteConditionalFormatRuleRequest
從清單中移除指定索引的規則。
範例
以下範例說明如何建立本頁頂端螢幕截圖中顯示的條件式格式設定。如需其他範例,請參閱「條件式格式設定」範例頁面。
Apps Script
/** * conditional formatting * @param {string} spreadsheetId spreadsheet ID * @returns {*} spreadsheet */ Snippets.prototype.conditionalFormatting = (spreadsheetId) => { try { let myRange = Sheets.newGridRange(); myRange.sheetId = 0; myRange.startRowIndex = 0; myRange.endRowIndex = 11; myRange.startColumnIndex = 0; myRange.endColumnIndex = 4; // Request 1 let rule1ConditionalValue = Sheets.newConditionValue(); rule1ConditionalValue.userEnteredValue = '=GT($D2,median($D$2:$D$11))'; let rule1ConditionFormat = Sheets.newCellFormat(); rule1ConditionFormat.textFormat = Sheets.newTextFormat(); rule1ConditionFormat.textFormat.foregroundColor = Sheets.newColor(); rule1ConditionFormat.textFormat.foregroundColor.red = 0.8; let rule1Condition = Sheets.newBooleanCondition(); rule1Condition.type = 'CUSTOM_FORMULA'; rule1Condition.values = [rule1ConditionalValue]; let rule1BooleanRule = Sheets.newBooleanRule(); rule1BooleanRule.condition = rule1Condition; rule1BooleanRule.format = rule1ConditionFormat; let rule1 = Sheets.newConditionalFormatRule(); rule1.ranges = [myRange]; rule1.booleanRule = rule1BooleanRule; let request1 = Sheets.newRequest(); let addConditionalFormatRuleRequest1 = Sheets.newAddConditionalFormatRuleRequest(); addConditionalFormatRuleRequest1.rule = rule1; addConditionalFormatRuleRequest1.index = 0; request1.addConditionalFormatRule = addConditionalFormatRuleRequest1; // Request 2 let rule2ConditionalValue = Sheets.newConditionValue(); rule2ConditionalValue.userEnteredValue = '=LT($D2,median($D$2:$D$11))'; let rule2ConditionFormat = Sheets.newCellFormat(); rule2ConditionFormat.textFormat = Sheets.newTextFormat(); rule2ConditionFormat.textFormat.foregroundColor = Sheets.newColor(); rule2ConditionFormat.textFormat.foregroundColor.red = 1; rule2ConditionFormat.textFormat.foregroundColor.green = 0.4; rule2ConditionFormat.textFormat.foregroundColor.blue = 0.4; let rule2Condition = Sheets.newBooleanCondition(); rule2Condition.type = 'CUSTOM_FORMULA'; rule2Condition.values = [rule2ConditionalValue]; let rule2BooleanRule = Sheets.newBooleanRule(); rule2BooleanRule.condition = rule2Condition; rule2BooleanRule.format = rule2ConditionFormat; let rule2 = Sheets.newConditionalFormatRule(); rule2.ranges = [myRange]; rule2.booleanRule = rule2BooleanRule; let request2 = Sheets.newRequest(); let addConditionalFormatRuleRequest2 = Sheets.newAddConditionalFormatRuleRequest(); addConditionalFormatRuleRequest2.rule = rule2; addConditionalFormatRuleRequest2.index = 0; request2.addConditionalFormatRule = addConditionalFormatRuleRequest2; // Batch send the requests const requests = [request1, request2]; let batchUpdate = Sheets.newBatchUpdateSpreadsheetRequest(); batchUpdate.requests = requests; const response = Sheets.Spreadsheets.batchUpdate(batchUpdate, spreadsheetId); return response; } catch (err) { // TODO (developer) - Handle exception console.log('Failed with error %s', err.message); } };
Java
import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.sheets.v4.Sheets; import com.google.api.services.sheets.v4.SheetsScopes; import com.google.api.services.sheets.v4.model.AddConditionalFormatRuleRequest; import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetRequest; import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse; import com.google.api.services.sheets.v4.model.BooleanCondition; import com.google.api.services.sheets.v4.model.BooleanRule; import com.google.api.services.sheets.v4.model.CellFormat; import com.google.api.services.sheets.v4.model.Color; import com.google.api.services.sheets.v4.model.ConditionValue; import com.google.api.services.sheets.v4.model.ConditionalFormatRule; import com.google.api.services.sheets.v4.model.GridRange; import com.google.api.services.sheets.v4.model.Request; import com.google.api.services.sheets.v4.model.TextFormat; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; /* Class to demonstrate the use of Spreadsheet Conditional Formatting API */ public class ConditionalFormatting { /** * Create conditional formatting. * * @param spreadsheetId - Id of the spreadsheet. * @return updated changes count. * @throws IOException - if credentials file not found. */ public static BatchUpdateSpreadsheetResponse conditionalFormat(String spreadsheetId) throws IOException { /* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */ GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( credentials); // Create the sheets API client Sheets service = new Sheets.Builder(new NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) .setApplicationName("Sheets samples") .build(); List<GridRange> ranges = Collections.singletonList(new GridRange() .setSheetId(0) .setStartRowIndex(1) .setEndRowIndex(11) .setStartColumnIndex(0) .setEndColumnIndex(4) ); List<Request> requests = Arrays.asList( new Request().setAddConditionalFormatRule(new AddConditionalFormatRuleRequest() .setRule(new ConditionalFormatRule() .setRanges(ranges) .setBooleanRule(new BooleanRule() .setCondition(new BooleanCondition() .setType("CUSTOM_FORMULA") .setValues(Collections.singletonList( new ConditionValue().setUserEnteredValue( "=GT($D2,median($D$2:$D$11))") )) ) .setFormat(new CellFormat().setTextFormat( new TextFormat().setForegroundColor( new Color().setRed(0.8f)) )) ) ) .setIndex(0) ), new Request().setAddConditionalFormatRule(new AddConditionalFormatRuleRequest() .setRule(new ConditionalFormatRule() .setRanges(ranges) .setBooleanRule(new BooleanRule() .setCondition(new BooleanCondition() .setType("CUSTOM_FORMULA") .setValues(Collections.singletonList( new ConditionValue().setUserEnteredValue( "=LT($D2,median($D$2:$D$11))") )) ) .setFormat(new CellFormat().setBackgroundColor( new Color().setRed(1f).setGreen(0.4f).setBlue(0.4f) )) ) ) .setIndex(0) ) ); BatchUpdateSpreadsheetResponse result = null; try { // Execute the requests. BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest() .setRequests(requests); result = service.spreadsheets() .batchUpdate(spreadsheetId, body) .execute(); System.out.printf("%d cells updated.", result.getReplies().size()); } catch (GoogleJsonResponseException e) { // TODO(developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); } else { throw e; } } return result; } }
JavaScript
function conditionalFormatting(spreadsheetId, callback) { const myRange = { sheetId: 0, startRowIndex: 1, endRowIndex: 11, startColumnIndex: 0, endColumnIndex: 4, }; const requests = [{ addConditionalFormatRule: { rule: { ranges: [myRange], booleanRule: { condition: { type: 'CUSTOM_FORMULA', values: [{userEnteredValue: '=GT($D2,median($D$2:$D$11))'}], }, format: { textFormat: {foregroundColor: {red: 0.8}}, }, }, }, index: 0, }, }, { addConditionalFormatRule: { rule: { ranges: [myRange], booleanRule: { condition: { type: 'CUSTOM_FORMULA', values: [{userEnteredValue: '=LT($D2,median($D$2:$D$11))'}], }, format: { backgroundColor: {red: 1, green: 0.4, blue: 0.4}, }, }, }, index: 0, }, }]; const body = { requests, }; try { gapi.client.sheets.spreadsheets.batchUpdate({ spreadsheetId: spreadsheetId, resource: body, }).then((response) => { const result = response.result; console.log(`${result.replies.length} cells updated.`); if (callback) callback(response); }); } catch (err) { document.getElementById('content').innerText = err.message; return; } }
Node.js
/** * Conditionally formats a Spreadsheet. * @param {string} spreadsheetId A Spreadsheet ID. * @return {obj} spreadsheet information */ async function conditionalFormatting(spreadsheetId) { const {GoogleAuth} = require('google-auth-library'); const {google} = require('googleapis'); const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/spreadsheets', }); const service = google.sheets({version: 'v4', auth}); const myRange = { sheetId: 0, startRowIndex: 1, endRowIndex: 11, startColumnIndex: 0, endColumnIndex: 4, }; const requests = [ { addConditionalFormatRule: { rule: { ranges: [myRange], booleanRule: { condition: { type: 'CUSTOM_FORMULA', values: [{userEnteredValue: '=GT($D2,median($D$2:$D$11))'}], }, format: { textFormat: {foregroundColor: {red: 0.8}}, }, }, }, index: 0, }, }, { addConditionalFormatRule: { rule: { ranges: [myRange], booleanRule: { condition: { type: 'CUSTOM_FORMULA', values: [{userEnteredValue: '=LT($D2,median($D$2:$D$11))'}], }, format: { backgroundColor: {red: 1, green: 0.4, blue: 0.4}, }, }, }, index: 0, }, }, ]; const resource = { requests, }; try { const response = await service.spreadsheets.batchUpdate({ spreadsheetId, resource, }); console.log(`${response.data.replies.length} cells updated.`); return response; } catch (err) { // TODO (developer) - Handle exception throw err; } }
PHP
use Google\Client; use Google\Service\Drive; use Google\Service\Sheets\BatchUpdateSpreadsheetRequest; use Google\Service\Sheets\Request; function conditionalFormatting($spreadsheetId) { /* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */ $client = new Google\Client(); $client->useApplicationDefaultCredentials(); $client->addScope(Google\Service\Drive::DRIVE); $service = new Google_Service_Sheets($client); try{ $myRange = [ 'sheetId' => 0, 'startRowIndex' => 1, 'endRowIndex' => 11, 'startColumnIndex' => 0, 'endColumnIndex' => 4, ]; //execute the request $requests = [ new Google_Service_Sheets_Request([ 'addConditionalFormatRule' => [ 'rule' => [ 'ranges' => [ $myRange ], 'booleanRule' => [ 'condition' => [ 'type' => 'CUSTOM_FORMULA', 'values' => [ [ 'userEnteredValue' => '=GT($D2,median($D$2:$D$11))' ] ] ], 'format' => [ 'textFormat' => [ 'foregroundColor' => [ 'red' => 0.8 ] ] ] ] ], 'index' => 0 ] ]), new Google_Service_Sheets_Request([ 'addConditionalFormatRule' => [ 'rule' => [ 'ranges' => [ $myRange ], 'booleanRule' => [ 'condition' => [ 'type' => 'CUSTOM_FORMULA', 'values' => [ [ 'userEnteredValue' => '=LT($D2,median($D$2:$D$11))' ] ] ], 'format' => [ 'backgroundColor' => [ 'red' => 1, 'green' => 0.4, 'blue' => 0.4 ] ] ] ], 'index' => 0 ] ]) ]; $batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([ 'requests' => $requests ]); $response = $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest); printf("%d cells updated.", count($response->getReplies())); return $response; } catch(Exception $e) { // TODO(developer) - handle error appropriately echo 'Message: ' .$e->getMessage(); } }
Python
import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def conditional_formatting(spreadsheet_id): """ Creates the batch_update the user has access to. Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """ creds, _ = google.auth.default() # pylint: disable=maybe-no-member try: service = build("sheets", "v4", credentials=creds) my_range = { "sheetId": 0, "startRowIndex": 1, "endRowIndex": 11, "startColumnIndex": 0, "endColumnIndex": 4, } requests = [ { "addConditionalFormatRule": { "rule": { "ranges": [my_range], "booleanRule": { "condition": { "type": "CUSTOM_FORMULA", "values": [ { "userEnteredValue": ( "=GT($D2,median($D$2:$D$11))" ) } ], }, "format": { "textFormat": {"foregroundColor": {"red": 0.8}} }, }, }, "index": 0, } }, { "addConditionalFormatRule": { "rule": { "ranges": [my_range], "booleanRule": { "condition": { "type": "CUSTOM_FORMULA", "values": [ { "userEnteredValue": ( "=LT($D2,median($D$2:$D$11))" ) } ], }, "format": { "backgroundColor": { "red": 1, "green": 0.4, "blue": 0.4, } }, }, }, "index": 0, } }, ] body = {"requests": requests} response = ( service.spreadsheets() .batchUpdate(spreadsheetId=spreadsheet_id, body=body) .execute() ) print(f"{(len(response.get('replies')))} cells updated.") return response except HttpError as error: print(f"An error occurred: {error}") return error if __name__ == "__main__": # Pass: spreadsheet_id conditional_formatting("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k")
小茹
my_range = { sheet_id: 0, start_row_index: 1, end_row_index: 11, start_column_index: 0, end_column_index: 4 } requests = [{ add_conditional_format_rule: { rule: { ranges: [my_range], boolean_rule: { condition: { type: 'CUSTOM_FORMULA', values: [{ user_entered_value: '=GT($D2,median($D$2:$D$11))' }] }, format: { text_format: { foreground_color: { red: 0.8 } } } } }, index: 0 } }, { add_conditional_format_rule: { rule: { ranges: [my_range], boolean_rule: { condition: { type: 'CUSTOM_FORMULA', values: [{ user_entered_value: '=LT($D2,median($D$2:$D$11))' }] }, format: { background_color: { red: 1, green: 0.4, blue: 0.4 } } } }, index: 0 } }] body = { requests: requests } batch_update = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new batch_update.requests = requests result = service.batch_update_spreadsheet(spreadsheet_id, batch_update) puts "#{result.replies.length} cells updated."