将多种字体颜色应用于单个 Google 表格单元格中的文本

Apply multiple font colors to the text in a single Google Sheets cell

我正在尝试使用 Google Apps 脚本中的函数将单元格格式化为具有多种字体颜色。我找不到关于它的任何文档。此外,使用 getFontColor() 没有 return 任何有用的东西。

有没有办法以编程方式重现此功能

用户可以通过 Google 表格网络 UI?

Sheets API is a bit daunting to start using, but allows very fine-grained control over your spreadsheets. You'll have to enable it, as it is an "Advanced Service". I strongly recommend reviewing the Sample Codelab.

使用表格 API,TextFormatRun 属性 可以在 cell-by-cell 的基础上进行操作。注:

Runs of rich text applied to subsections of the cell. Runs are only valid on user entered strings, not formulas, bools, or numbers. Runs start at specific indexes in the text and continue until the next run. Properties of a run will continue unless explicitly changed in a subsequent run (and properties of the first run will continue the properties of the cell unless explicitly changed).

When writing, the new runs will overwrite any prior runs. When writing a new userEnteredValue, previous runs will be erased.

此示例使用它来调整文本的绿色值,在活动单元格中的字符串长度范围内从 0% 增加到 100%。根据您的需要进行调整。

function textFormatter() {
  // Get the current cell's text.
  var wb = SpreadsheetApp.getActive(), sheet = wb.getActiveSheet();
  var cell = sheet.getActiveCell(), value = cell.getValue();
  var len = value.toString().length;
  if(len == 0) return;

  // Change the color every 2 characters.
  var newCellData = Sheets.newCellData();
  newCellData.textFormatRuns = [];
  var step = 1 / len;
  for(var c = 0; c < len; c += 2) {
    var newFmt = Sheets.newTextFormatRun();
    newFmt.startIndex = c;
    newFmt.format = Sheets.newTextFormat();
    newFmt.format.foregroundColor = Sheets.newColor();
    newFmt.format.foregroundColor.green = (c + 2) * step;
    newCellData.textFormatRuns.push(newFmt);
  }

  // Create the request object.
  var batchUpdateRQ = Sheets.newBatchUpdateSpreadsheetRequest();
  batchUpdateRQ.requests = [];
  batchUpdateRQ.requests.push(
    {
       "updateCells": {
        "rows": [ { "values": newCellData } ],
        "fields": "textFormatRuns",
        "start": {
          "sheetId": sheet.getSheetId(),
          "rowIndex": cell.getRow() - 1,
          "columnIndex": cell.getColumn() - 1
        }
      }
    }
  );
  Sheets.Spreadsheets.batchUpdate(batchUpdateRQ, wb.getId());
}

编辑:根据要设置格式的单元格值的设置方式,可能还需要在同一请求中包含单元格的值。 See this example on the issue tracker

自 2018 年 7 月起,Apps-Script 支持更改单个文本颜色和其他字体相关样式。 SpreadsheetApp 添加了两个方法。 newTextStyle()newRichTextValue()。以下应用程序脚本更改 A1 中的此类字体样式。为获得最佳效果,请使用较长的字符串(30 个字符或更多)。

function rainbow(){
  var rng = SpreadsheetApp.getActiveSheet().getRange("A1");
  var val = rng.getValue().toString();
  var len = val.length; // length of string in A1
  var rich = SpreadsheetApp.newRichTextValue(); //new RichText
  rich.setText(val); //Set Text value in A1 to RichText as base 
  for (var i=0;i<len;i++){ //Loop through each character
    var style = SpreadsheetApp.newTextStyle(); // Create a new text style for each character
    var red= ("0"+Math.round((1/len)*(i)*255).toString(16)).substr(-2,2); //
    var green= ("0"+Math.round((1/len)*Math.min(i*2,len-Math.abs(i*2-len))*255).toString(16)).substr(-2,2); //
    var blue= ("0"+Math.round((1/len)*(len-i)*255).toString(16)).substr(-2,2);//
    style.setForegroundColor("#"+red+green+blue); // hexcode
    style.setFontSize(Math.max(Math.abs(len/2-i),8)); //Use a lengthy string
    var buildStyle = style.build(); 
    rich.setTextStyle(i,i+1,buildStyle); // set this text style to the current character and save it to Rich text     
  }
  var format = rich.build()
  rng.setRichTextValue(format); //Set the final RichTextValue to A1
}

文档尚未发布。方法可能会发生变化

参考文献:

requests = [
   
 object = {
            
    "updateCells": {
       "range": {
            "sheetId": sheetId,
            
             "startRowIndex":startRowIndex,
             "endRowIndex": endRowIndex,
            
             "startColumnIndex": startColumnIndex,
                        
             "endColumnIndex": endColumnIndex
            
            }
      "rows": [{
          "values": [{
              "textFormatRuns": [
             
                  {"format": {
            
                    "foregroundColor": {
             
                       "red": 0.0,
            
                       "green": 255.0,
            
                       "blue": 31.0
            
                    },
            
                 },"startIndex": 0
             
             },
            
           ]
            
         }
            
        ]
            
      }]
    "fields": "textFormatRuns(format)"
            
    }
           
 }
]
 
    try:
            
       result = service.spreadsheets().batchUpdate(spreadsheetId=internamiento_id, 
       body={'requests': requests}).execute()
            
       print('{0} celdas actualizadas'.format(result.get('totalUpdatedCells')))
        
        except Exception as e:
            print(e)
            json_salida["error"] = "Ocurrio un error "
            
    return json_salida, 400

该函数将生成文本,然后遍历所有单元格突出显示所选单词。所以你可以 运行 它在空白处 sheet 来弄清楚它是如何工作的。它还处理多种颜色。

function highlightword() {
  const red = SpreadsheetApp.newTextStyle().setForegroundColor('red').build();
  const org = SpreadsheetApp.newTextStyle().setForegroundColor('orange').build();
  const blu = SpreadsheetApp.newTextStyle().setForegroundColor('blue').build();
  const cA = [red,org,blu];//colors array
  const sA = ['Mimi id sweet litter wiener dog', 'Cooper died and we both miss him', 'Vony died to and I really miss her.', 'Someday fairly soon I will probably die.'];
  const wordA = ['sweet', 'dog', 'died', 'fairly', 'little', 'and','Mimi','Cooper'];
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');
  const rg = sh.getRange(1, 1, 10, 5);
  let vs = rg.getValues();
  rg.clearContent();
  const dA = vs.map((r, i) => {
    let row = [...Array(rg.getWidth()).keys()].map(i => sA[Math.floor(Math.random() * sA.length)]);
    return row.slice();
  });
  rg.setValues(dA);
  //End of sample text generation
  SpreadsheetApp.flush();
  dA.forEach((r, i) => {
    r.forEach((c, j) => {
      let idxObj = { pA: [] };
      wordA.forEach(w => {
        let idx = c.indexOf(w);
        if (~idx) {
          idxObj[w] = idx;
          idxObj.pA.push(w);
        }
      });
      if (idxObj.pA.length > 0) {
        let cell = sh.getRange(i + 1, j + 1);
        let val = SpreadsheetApp.newRichTextValue().setText(c);
        idxObj.pA.forEach((p,k) => {
          val.setTextStyle(idxObj[p], idxObj[p] + p.length, cA[k % cA.length]);
        });
        cell.setRichTextValue(val.build());
      }
    });
  });
}