Google 工作表设置下划线 (offsetBegin, offsetEnd)

Google Sheets setUnderline (offsetBegin, offsetEnd)

有谁知道在 Google 表格单元格中给部分文本加下划线的方法吗?我真的在寻找一个像我对这个查询的标题的功能。

我玩过 .getDisplayValue,范围 class 的 .getValue,并尝试查看是否可以从 Google 工作表访问文档文本 Class,但没有成功。我知道我可以直接从 Google 表格中执行此操作,但需要从 Google Apps Scripts (GAS) 中使用此功能。

我也知道实际电子表格编辑器中的这项功能是新功能,Apps 脚本可能需要赶上。

感谢您的任何回复。

特里

尝试使用下面的函数为您的字符串应用下划线。不幸的是,Google 表格似乎不支持连续下划线。

function underline(string, start, end) {

  start = start || 0;
  end = end || string.length;

  var res = "";

  for (var i=start; i < end; i++) {

    res += string.charAt(i) + "\u0332";

  }

  return res.toString();

}

请参阅 https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#CellData and https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#TextFormatRun 了解如何执行此操作。

如果需要,请参阅 https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#RepeatCellRequest 了解如何一次将格式应用于多个单元格。

我个人没有尝试过 TextFormatRun 功能,但作为一个更通用的示例,这里是您如何更改背景和前景的颜色、对齐方式和一行的粗体:

def sheets_batch_update(SHEET_ID,data):
    print ( ("Sheets: Batch update"))
    service.spreadsheets().batchUpdate(spreadsheetId=SHEET_ID,body=data).execute() #,valueInputOption='RAW'

data={
  "requests": [

#format header row
    {
      "repeatCell": {
        "range": {
          "sheetId": all_sheets['Users'],
          "startRowIndex": 0,
          "endRowIndex": 1
#           "startColumnIndex": 0,
#           "endColumnIndex": 6
        },
        "cell": {
          "userEnteredFormat": {
            "backgroundColor": {
              "red": 0.4,
              "green": 0.4,
              "blue": 0.4
            },
            "horizontalAlignment" : "LEFT",
            "textFormat": {
              "foregroundColor": {
                "red": 1.0,
                "green": 1.0,
                "blue": 1.0
              },
              #"fontSize": 12,
              "bold": True
            }
          }
        },
        "fields": "userEnteredFormat(backgroundColor,textFormat,horizontalAlignment)"
      }
    },


  ]
}

sheets_batch_update(SHEET_ID, data)

您现在可以在 GAS 中设置下划线。

function underline(startOffset,endOffset){
startOffset = startOffset || 1;
endOffset = endOffset || 3;
  var rng = SpreadsheetApp.getActiveSheet().getRange("A1");
  var val = rng.getValue().toString();
  var rich = SpreadsheetApp.newRichTextValue(); //new RichText
  rich.setText(val); //Set Text value in A1 to RichText
    var style = SpreadsheetApp.newTextStyle(); // Create a new text style
    style.setUnderline(true);
    var buildStyle = style.build(); 
    rich.setTextStyle(startOffset,endOffset,buildStyle); // set this text style to the offset character range and save it to Rich text     
  var format = rich.build()
  rng.setRichTextValue(format); //Set the final RichTextValue back to A1
}