簡體   English   中英

將多種字體顏色應用於單個 Google 表格單元格中的文本

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

我正在嘗試使用 Google Apps Script 中的函數將單元格格式化為具有多種字體顏色。 我找不到任何關於它的文檔。 此外,使用getFontColor()不會返回任何有用的東西。

有沒有辦法以編程方式重現此功能

在此處輸入圖片說明

用戶可以通過 Google Sheets Web UI 使用它嗎?

自 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
}

文檔尚未發布。 方法可能會發生變化

參考:

Sheets API開始使用有點令人生畏,但允許對電子表格進行非常細粒度的控制。 您必須啟用它,因為它是一項“高級服務”。 我強烈建議您查看示例 Codelab

使用 Sheets API,可以逐個單元地操作TextFormatRun屬性。 筆記:

應用於單元格子部分的富文本運行。 運行僅對用戶輸入的字符串有效,對公式、布爾值或數字無效。 運行從文本中的特定索引開始,一直持續到下一次運行。 除非在后續運行中明確更改,否則運行的屬性將繼續(除非明確更改,否則第一次運行的屬性將繼續單元格的屬性)。

寫入時,新運行將覆蓋任何先前運行。 寫入新的 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());
}

編輯:根據要設置格式的單元格的值的設置方式,可能還需要在同一請求中包含單元格的值。 在問題跟蹤器上查看此示例

該函數將生成文本,然后通過所有單元格突出顯示所選單詞。 所以你可以在一張白紙上運行它來弄清楚它是如何工作的。

function highlightword() {
  const sA = ['Mimi id sweet litter wiener dog', 'Cooper died and we both miss him', 'Von died to and I really miss her.', 'Someday fairly soon I will probably die.'];
  const wordA = ['sweet', 'dog', 'died','fairly'];
  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);
  dA.forEach((r, i) => {
    r.forEach((c, j) => {
      wordA.forEach(w => {
        let idx = c.indexOf(w);
        if (~idx) {
          let cell = sh.getRange(i + 1, j + 1);
          let red = SpreadsheetApp.newTextStyle().setForegroundColor('red').build();
          let val = SpreadsheetApp.newRichTextValue()
            .setText(c)
            .setTextStyle(idx, idx + w.length, red)
            .build();
          cell.setRichTextValue(val);
        }
      });
    });
  });
}
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM