सशर्त फ़ॉर्मेटिंग

शर्त के साथ फ़ॉर्मैटिंग की सुविधा का इस्तेमाल करके, सेल को फ़ॉर्मैट किया जा सकता है. इससे सेल में मौजूद वैल्यू या अन्य सेल में मौजूद वैल्यू के हिसाब से, सेल का लुक डाइनैमिक तरीके से बदलता है. शर्त के साथ फ़ॉर्मैटिंग का इस्तेमाल कई तरीकों से किया जा सकता है. जैसे:

  • किसी थ्रेशोल्ड से ऊपर की सेल को हाइलाइट करें. उदाहरण के लिए, 2,000 डॉलर से ज़्यादा के सभी लेन-देन के लिए बोल्ड टेक्स्ट का इस्तेमाल करें.
  • सेल को इस तरह से फ़ॉर्मैट करें कि उनकी वैल्यू के हिसाब से उनका रंग बदलता रहे. उदाहरण के लिए, 2,000 डॉलर से ज़्यादा की रकम बढ़ने पर, ज़्यादा गहरे लाल रंग का बैकग्राउंड लागू करना.
  • अन्य सेल के कॉन्टेंट के आधार पर, सेल को डाइनैमिक तौर पर फ़ॉर्मैट करना. उदाहरण के लिए, उन प्रॉपर्टी के पते को हाइलाइट करना जिनका "बाज़ार में उपलब्ध रहने की अवधि" फ़ील्ड > 90 दिन है.

सेल की वैल्यू और अन्य सेल की वैल्यू के आधार पर भी सेल को फ़ॉर्मैट किया जा सकता है. उदाहरण के लिए, किसी रेंज की मीडियन वैल्यू की तुलना में सेल की वैल्यू के आधार पर, सेल की किसी रेंज को फ़ॉर्मैट किया जा सकता है:

माध्यिका उम्र से ज़्यादा या कम उम्र वाली वैल्यू को हाइलाइट करने के लिए फ़ॉर्मैटिंग.

पहली इमेज. माध्यिका उम्र से ज़्यादा या कम उम्र वाली वैल्यू को हाइलाइट करने के लिए फ़ॉर्मैटिंग.

इस उदाहरण में, हर लाइन की सेल को इस तरह से फ़ॉर्मैट किया गया है कि उनकी age कॉलम की वैल्यू की तुलना, सभी उम्र की मीडियन वैल्यू से की जा सके. जिन लाइनों की उम्र औसत से ज़्यादा है उनका टेक्स्ट लाल रंग का है. वहीं, जिनकी उम्र औसत से कम है उनका बैकग्राउंड लाल रंग का है. दो लाइनों में age की वैल्यू, औसत उम्र (48) से मेल खाती है. इन सेल को कोई खास फ़ॉर्मैट नहीं दिया गया है. (शर्त के साथ फ़ॉर्मैटिंग बनाने वाले सोर्स कोड के लिए, यहां दिया गया उदाहरण देखें.)

कंडिशनल फ़ॉर्मैटिंग के नियम

कंडिशनल फ़ॉर्मैटिंग को फ़ॉर्मैटिंग के नियमों का इस्तेमाल करके दिखाया जाता है. हर स्प्रेडशीट में, इन नियमों की सूची सेव होती है. साथ ही, ये नियम उसी क्रम में लागू होते हैं जिस क्रम में ये सूची में दिखते हैं. Google Sheets API की मदद से, फ़ॉर्मैटिंग के इन नियमों को जोड़ा, अपडेट किया, और मिटाया जा सकता है.

हर नियम में, टारगेट रेंज, नियम का टाइप, नियम को ट्रिगर करने की शर्तें, और लागू होने वाला फ़ॉर्मैट शामिल होता है.

टारगेट रेंज—यह एक सेल, सेल की रेंज या कई रेंज हो सकती है.

नियम का टाइप—नियम दो कैटगरी के होते हैं:

  • बूलियन नियमों के तहत, फ़ॉर्मैट सिर्फ़ तब लागू होता है, जब कुछ खास शर्तें पूरी होती हैं.
  • ग्रेडिएंट के नियम, सेल की वैल्यू के आधार पर सेल के बैकग्राउंड के रंग का हिसाब लगाते हैं.

इन नियमों के टाइप के लिए, जिन शर्तों का आकलन किया जाता है और जिन फ़ॉर्मैट को लागू किया जा सकता है वे अलग-अलग होते हैं. इनके बारे में यहां बताया गया है.

बूलियन नियम

BooleanRule यह तय करता है कि किसी खास फ़ॉर्मैट को लागू करना है या नहीं. यह फ़ैसला, BooleanCondition के आधार पर लिया जाता है. BooleanCondition का आकलन true या false के तौर पर किया जाता है. बूलियन नियम इस तरह से होता है:

{
  "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

sheets/api/spreadsheet_snippets.gs
/**
 * conditional formatting
 * @param {string} spreadsheetId spreadsheet ID
 * @returns {*} spreadsheet
 */
Snippets.prototype.conditionalFormatting = (spreadsheetId) => {
  try {
    const myRange = Sheets.newGridRange();
    myRange.sheetId = 0;
    myRange.startRowIndex = 0;
    myRange.endRowIndex = 11;
    myRange.startColumnIndex = 0;
    myRange.endColumnIndex = 4;

    // Request 1
    const rule1ConditionalValue = Sheets.newConditionValue();
    rule1ConditionalValue.userEnteredValue = "=GT($D2,median($D$2:$D$11))";

    const rule1ConditionFormat = Sheets.newCellFormat();
    rule1ConditionFormat.textFormat = Sheets.newTextFormat();
    rule1ConditionFormat.textFormat.foregroundColor = Sheets.newColor();
    rule1ConditionFormat.textFormat.foregroundColor.red = 0.8;

    const rule1Condition = Sheets.newBooleanCondition();
    rule1Condition.type = "CUSTOM_FORMULA";
    rule1Condition.values = [rule1ConditionalValue];

    const rule1BooleanRule = Sheets.newBooleanRule();
    rule1BooleanRule.condition = rule1Condition;
    rule1BooleanRule.format = rule1ConditionFormat;

    const rule1 = Sheets.newConditionalFormatRule();
    rule1.ranges = [myRange];
    rule1.booleanRule = rule1BooleanRule;

    const request1 = Sheets.newRequest();
    const addConditionalFormatRuleRequest1 =
      Sheets.newAddConditionalFormatRuleRequest();
    addConditionalFormatRuleRequest1.rule = rule1;
    addConditionalFormatRuleRequest1.index = 0;
    request1.addConditionalFormatRule = addConditionalFormatRuleRequest1;

    // Request 2
    const rule2ConditionalValue = Sheets.newConditionValue();
    rule2ConditionalValue.userEnteredValue = "=LT($D2,median($D$2:$D$11))";

    const 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;

    const rule2Condition = Sheets.newBooleanCondition();
    rule2Condition.type = "CUSTOM_FORMULA";
    rule2Condition.values = [rule2ConditionalValue];

    const rule2BooleanRule = Sheets.newBooleanRule();
    rule2BooleanRule.condition = rule2Condition;
    rule2BooleanRule.format = rule2ConditionFormat;

    const rule2 = Sheets.newConditionalFormatRule();
    rule2.ranges = [myRange];
    rule2.booleanRule = rule2BooleanRule;

    const request2 = Sheets.newRequest();
    const addConditionalFormatRuleRequest2 =
      Sheets.newAddConditionalFormatRuleRequest();
    addConditionalFormatRuleRequest2.rule = rule2;
    addConditionalFormatRuleRequest2.index = 0;
    request2.addConditionalFormatRule = addConditionalFormatRuleRequest2;

    // Batch send the requests
    const requests = [request1, request2];
    const 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

sheets/snippets/src/main/java/ConditionalFormatting.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

sheets/snippets/sheets_conditional_formatting.js
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

sheets/snippets/sheets_conditional_formatting.js
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Applies conditional formatting to a spreadsheet.
 * @param {string} spreadsheetId The ID of the spreadsheet.
 * @return {Promise<object>} The response from the batch update.
 */
async function conditionalFormatting(spreadsheetId) {
  // Authenticate with Google and get an authorized client.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/spreadsheets',
  });

  // Create a new Sheets API client.
  const service = google.sheets({version: 'v4', auth});

  // The range to apply the conditional formatting to.
  const myRange = {
    sheetId: 0,
    startRowIndex: 1,
    endRowIndex: 11,
    startColumnIndex: 0,
    endColumnIndex: 4,
  };

  // The requests to apply conditional formatting.
  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,
      },
    },
  ];

  // Create the batch update request.
  const resource = {
    requests,
  };

  // Execute the batch update request.
  const response = await service.spreadsheets.batchUpdate({
    spreadsheetId,
    resource,
  });
  console.log(`${response.data.replies.length} cells updated.`);
  return response;
}

PHP

sheets/snippets/src/SpreadsheetConditionalFormatting.php
<?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

sheets/snippets/sheets_conditional_formatting.py
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")

Ruby

sheets/snippets/lib/spreadsheet_snippets.rb
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."