Google apps script 将多个字体颜色应用于单个Google Sheets单元格中的文本

Google apps script 将多个字体颜色应用于单个Google Sheets单元格中的文本,google-apps-script,google-sheets,text-formatting,Google Apps Script,Google Sheets,Text Formatting,我正在尝试使用谷歌应用程序脚本中的一个函数格式化一个单元格,使其具有多种字体颜色。我找不到关于它的任何文件。另外,使用getFontColor()不会返回任何有用的信息 有没有办法以编程方式重现此功能 用户可以通过Google Sheets web UI使用它?开始使用它有点让人望而生畏,但它允许对电子表格进行非常细粒度的控制。你必须这样做,因为这是一项“高级服务”。我强烈建议您重新检查 使用Sheets API,可以逐个单元格操作属性。注: 应用于单元格子部分的富文本运行。运行仅对用户输入的

我正在尝试使用谷歌应用程序脚本中的一个函数格式化一个单元格,使其具有多种字体颜色。我找不到关于它的任何文件。另外,使用
getFontColor()
不会返回任何有用的信息

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

用户可以通过Google Sheets web UI使用它?

开始使用它有点让人望而生畏,但它允许对电子表格进行非常细粒度的控制。你必须这样做,因为这是一项“高级服务”。我强烈建议您重新检查

使用Sheets API,可以逐个单元格操作属性。注:

应用于单元格子部分的富文本运行。运行仅对用户输入的字符串有效,而对公式、布尔值或数字无效。运行从文本中的特定索引开始,并持续到下一次运行。除非在后续运行中显式更改,否则运行的属性将继续(第一次运行的属性将继续单元格的属性,除非显式更改)

写入时,新运行将覆盖以前的所有运行。写入新的userEnteredValue时,以前的运行将被擦除

本例使用它来调整文本的绿色值,在活动单元格中字符串的长度上从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());
}
函数textFormatter(){
//获取当前单元格的文本。
var wb=SpreadsheetApp.getActive(),sheet=wb.getActiveSheet();
var cell=sheet.getActiveCell(),value=cell.getValue();
var len=value.toString().length;
如果(len==0)返回;
//每2个字符更改一次颜色。
var newCellData=Sheets.newCellData();
newCellData.textFormatRuns=[];
var阶跃=1/len;
对于(var c=0;c


编辑:根据要格式化的单元格的值的设置方式,可能还需要在同一请求中包含单元格的值

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

函数彩虹(){
var rng=SpreadsheetApp.getActiveSheet().getRange(“A1”);
var val=rng.getValue().toString();
var len=val.length;//A1中字符串的长度
var rich=SpreadsheetApp.newRichTextValue();//new RichText
rich.setText(val);//将A1中的文本值设置为RichText作为基

对于(var i=0;i@tehhowch是的,除了格式化整个单元格外,我无法对单个文本元素取得任何进展。我认为您需要类似的方法。本机应用程序脚本中的简化工作表API无法执行复杂的格式化,因此您需要启用高级工作表服务,然后应用A我不相信这会允许我单独给文本上色,我看到他们可以用unicode加下划线,但我不相信对颜色也可以这样做。我认为这符合你的要求needs@I“-”I您需要在提供
textFormatRun
信息的
updateCells
请求中提供值(如链接示例中所述)。在阅读时也可以检索此多格式数据吗?我很难知道是否可以进行阅读。@atralb是的,您可以专门查询。在我写下此答案后的一段时间,本机应用程序脚本电子表格服务用相关的富文本方法进行了更新。readin有一个类似的Sheets API方法g文本也可以运行。你能编辑你的答案来解释它是如何工作的吗?
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); //
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