You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Apps Script实现Google Sheets单元格多字体颜色设置?

How to Implement Multi-Color Text in Google Sheets with Apps Script

Absolutely! You can totally replicate the multi-color text functionality available in the Google Sheets web UI using Google Apps Script—you just need to work with the right API methods, since getFontColor() only returns the default font color of the cell, not the per-character styling you're looking for.

Setting Multi-Color Text in a Cell

The key here is using the RichTextValue class and its builder to apply different colors to specific parts of the cell's text. Here's a straightforward example:

function setMultiColorCellText() {
  const activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const targetCell = activeSheet.getRange("A1");
  
  // Build your styled text
  const styledText = SpreadsheetApp.newRichTextValue()
    .setText("Let's make this: RED, BLUE, GREEN")
    // Color "RED" (characters 15-18) bright red
    .setForegroundColor(15, 18, "#ff0000")
    // Color "BLUE" (characters 20-24) dark blue
    .setForegroundColor(20, 24, "#00008b")
    // Color "GREEN" (characters 26-31) forest green
    .setForegroundColor(26, 31, "#228b22")
    .build();
  
  // Apply the styled text to the cell
  targetCell.setRichTextValue(styledText);
}

Retrieving Multi-Color Text Styles

Since getFontColor() doesn't capture per-character colors, use getRichTextValue() to access the full styled content, then iterate over its text "runs" (segments with consistent styling):

function getMultiColorStyles() {
  const activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const targetCell = activeSheet.getRange("A1");
  const richText = targetCell.getRichTextValue();
  const textRuns = richText.getRuns();
  
  // Log each segment's text and its color
  textRuns.forEach((run, index) => {
    const segmentText = run.getText();
    const segmentColor = run.getForegroundColor();
    console.log(`Segment ${index + 1}: "${segmentText}" | Color: ${segmentColor}`);
  });
}

Important Notes

  • The setForegroundColor(startOffset, endOffset, color) method uses zero-based, exclusive end indices. For example, 0, 5 targets characters 0 through 4.
  • You can use hex codes, RGB values (via SpreadsheetApp.newColor().setRgb(255, 0, 0).build()), or named colors like "orange".
  • This same approach works for other text styles too—chain methods like .setBold(startOffset, endOffset, true) or .setFontSize(startOffset, endOffset, 14) to combine formatting.

内容的提问来源于stack exchange,提问作者MGomeyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:04:50