How to Format a Part of a Google Sheets Cell Value Using Google APIs

Abstract: Apply bold or color to specific character ranges within a Google Sheets cell using the spreadsheets.batchUpdate API and textFormatRuns.

Created: 2026-09-08 by

You cannot format a substring of a cell value using standard value updates because Google Sheets treats the entire content as either plain text or a formula. To achieve this, you must use the spreadsheets.batchUpdate method with a CellFormat request that targets specific character indices via textFormatRuns. This approach allows you to apply styles like bolding or color to only parts of the string within a single cell.Understanding the Limitation of Value Updates

A common misconception is that one can update the visual style of a portion of a cell by simply sending a new value object. In reality, the spreadsheets.values.update endpoint only handles the data itself, not the presentation layer. When you send a value, it replaces the existing content entirely, and any previous formatting is lost unless explicitly reapplied to the whole cell.

To format just a part of a cell, such as making the first word red and the rest black, you need to interact with the rendering properties directly. The Google Sheets API provides the BatchUpdateSpreadsheetRequest for this purpose. Specifically, you will use the repeatCell action combined with a CellFormat structure that includes textFormatRuns.

Constructing the Text Format Run

The core mechanism for partial formatting is the textFormatRun. This object defines a range of characters and the style applied to them. It requires two main components: the startIndex and the endIndex, which define the slice of the string, and the format object containing the desired styles.

Indices in the Google Sheets API are zero-based and inclusive for the start index, but exclusive for the end index. For example, if your cell contains "Hello World" and you want to format "Hello", you would set startIndex to 0 and endIndex to 5. Note that spaces count towards the index length. If you have multiple distinct formats, you can provide an array of these runs, ensuring they do not overlap and cover the necessary characters.

Inside the format object, you can specify various attributes such as bold, italic, fontFamily, and foregroundColor. The foreground color is specified using RGB values where each component ranges from 0 to 1. This precision allows for nuanced styling that matches your application's design system.

Implementing with Node.js

Using the googleapis library in Node.js simplifies the authentication and request process. You first need to initialize the Sheets service with appropriate credentials. Then, you construct the request payload carefully. The payload must include the spreadsheet ID, the sheet ID (which can be found in the URL or retrieved via a separate call), and the range of the cell being updated.

Here is how you structure the request body:

const { google } = require('googleapis');
const sheets = google.sheets({ version: 'v4', auth });

await sheets.spreadsheets.batchUpdate({
  spreadsheetId: SPREADSHEET_ID,
  resource: {
    requests: [
      {
        repeatCell: {
          range: {
            sheetId: SHEET_ID,
            startIndex: 0, // Column A
            endIndex: 1,   // Column B
            rowIndex: ROW_INDEX,
          },
          cell: {
            userEnteredFormat: {
              textFormatRuns: [
                {
                  startIndex: 0,
                  endIndex: 5,
                  format: {
                    bold: true,
                    foregroundColor: {
                      red: 1,
                      green: 0,
                      blue: 0,
                    },
                  },
                },
              ],
            },
          },
          fields: 'userEnteredFormat.textFormatRuns',
        },
      },
    ],
  },
});

Notice the fields parameter. It is crucial to specify exactly which fields you are updating. By setting it to 'userEnteredFormat.textFormatRuns', you ensure that only the text format runs are modified, leaving other cell properties like borders or background colors untouched. Omitting this or setting it incorrectly can lead to unexpected overwrites.

Handling Dynamic Content

In many real-world scenarios, the content of the cell is dynamic, meaning the length of the text changes. Calculating the correct startIndex and endIndex becomes critical. If you are parsing a structured string, such as a JSON payload or a delimited list, you should calculate these indices programmatically before sending the API request.

For instance, if you are highlighting keywords in a search result, you might iterate through the string to find the positions of those keywords. Each occurrence would generate a separate textFormatRun entry in the array. Ensure that your logic accounts for Unicode characters correctly, as some languages may use surrogate pairs that affect byte counts versus character counts. The Google Sheets API uses UTF-16 code units for indexing, so standard JavaScript string methods like substring work well for determining lengths.

If you are dealing with formulas, remember that textFormatRuns apply to the displayed value, not the formula text itself. If the formula returns a different result than what was originally typed, the formatting will adjust to the new displayed value based on the indices provided. This behavior is generally desirable as it maintains the visual intent regardless of the underlying data change.

Common Pitfalls and Debugging

One frequent error is providing overlapping ranges in textFormatRuns. The API will reject the request if two runs try to style the same character differently. Always validate your ranges before sending the request. Another issue is forgetting to include the fields mask. Without it, the API might not know which part of the CellFormat to update, potentially ignoring your changes or resetting other properties.

Additionally, ensure that the cell actually contains text. Formatting runs on empty cells or numeric-only cells without text representation may have no visible effect. If you are applying formatting to a cell that contains a number formatted as text, the indices still refer to the textual representation. This consistency helps in maintaining predictable behavior across different data types.

Frequently Asked Questions

Can I format a cell using the Google Sheets UI instead of the API?

The Google Sheets interface does not allow direct formatting of substrings within a single cell. You must manually split the content into multiple cells or use conditional formatting rules that apply to the entire cell. The API is the only programmatic way to achieve granular, substring-level styling.

What happens if my textFormatRuns overlap?

The API will return a validation error and reject the batch update. You must ensure that each character index is covered by at most one run. If you need complex overlapping styles, consider restructuring your data into separate cells or using HTML-like tags if supported by future API features.

Does this method work for cells containing formulas?

Yes, but the formatting applies to the evaluated result, not the formula bar text. If the formula output changes, the indices you provided might no longer align with the desired text segments. You may need to recalculate indices dynamically when the formula result changes.

How do I specify a hex color code?

The API does not accept hex codes directly. You must convert the hex color to its RGB components normalized between 0 and 1. For example, white (#FFFFFF) becomes red: 1, green: 1, blue: 1. Black (#000000) becomes all zeros. Use a simple conversion script to handle this transformation.

Is there a limit to the number of textFormatRuns per cell?

There is a practical limit based on the total size of the request and the complexity of the cell. While there is no explicit small integer cap documented, excessively large arrays of runs can cause performance issues or timeout errors. Keep the number of runs reasonable and test with typical data volumes.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More