如何在 Google-apps-script 中将格式化文本转换为 html 标签?

lou*_*udo 2 google-sheets google-apps-script

我想将单元格中的格式化文本转换为 html,但我不知道如何读取文本的格式。

假设单元格中有以下文本:带有粗体字的文本。

我想将其在其他单元格中转换为:带有<b>粗体</b>字的文本。

我怎样才能做到这一点?

我在电子表格 API 中没有找到任何有用的内容来读取格式信息...有人有任何提示吗?谢谢。

编辑:我创建了一个功能请求。请投票以拥有该功能。

Edu*_*omo 5

我的谷歌脚本

/**
 * Rich Text to HTML.
 * @param {string} qRange Input text.
 * @returns {string} Text as HTML.
 * @customfunction
 */
function RICHTEXT_TO_HTML(qRange) {
  var indexBool = false;
  var indexItalic = false;
  var indexUnderline = false;
  var indexStrikethrough = false;

  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange(qRange);
  var cell = range;
  var cellValue = cell.getRichTextValue();
  var txt = String(cell.getDisplayValue());
  var styles = cell.getTextStyles();
  var result = '';

  for (var i = 0; i < txt.length; i++) {
    var style = cellValue.getTextStyle(i, i + 1);

    if (!indexStrikethrough && style.isStrikethrough()) {
      indexStrikethrough = true;
      result += '<strike>';
    } else if (indexStrikethrough && !style.isStrikethrough()) {
      indexStrikethrough = false;
      result += '</strike>';
    }

    if (!indexUnderline && style.isUnderline()) {
      indexUnderline = true;
      result += '<u>';
    } else if (indexUnderline && !style.isUnderline()) {
      indexUnderline = false;
      result += '</u>';
    }

    if (!indexBool && style.isBold()) {
      indexBool = true;
      result += '<b>';
    } else if (indexBool && !style.isBold()) {
      indexBool = false;
      result += '</b>';
    }

    if (!indexItalic && style.isItalic()) {
      indexItalic = true;
      result += '<i>';
    } else if (indexItalic && !style.isItalic()) {
      indexItalic = false;
      result += '</i>';
    }

    result += txt[i];
  }

  if (indexStrikethrough) {
    result += '</strike>';
  }

  if (indexUnderline) {
    result += '</u>';
  }

  if (indexBool) {
    result += '</b>';
  }

  if (indexItalic) {
    result += '</i>';
  }

  return result;
}
Run Code Online (Sandbox Code Playgroud)

用法

  • A1=“我的格式化 示例!!!”
  • A2==RICHTEXT_TO_HTML("A1")
  • A2结果=My <i>formatted</i> <b>example</b>!!!

工作示例

https://docs.google.com/spreadsheets/d/1mVvE8AdXYKSnaSIfRBrjfOeXxmTkVZovhguMZ3sc47M/edit?usp=sharing