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

时间:2017-01-27 16:55:00

标签: google-apps-script google-sheets

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

我们说我在单元格中有以下文字: 带有粗体字词的文字。

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

我该怎么做?

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

编辑:我创建了feature request。请投票赞成该功能。

3 个答案:

答案 0 :(得分:2)

我的 Google脚本

/**
 * 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;
}

用法

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

工作示例

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

答案 1 :(得分:0)

您需要使用Range的getFontWeight属性来读取这些格式化值。此处给出的示例:GAS-check-cell-format

检查Rucent88的答案。

答案 2 :(得分:0)

我继续更新了这个想法,以更好地反映我们在 2021 年如何做到这一点。

/**
 * @Author: Emma Sargent
 * Rich Text to HTML.
 * @param {Range} Google Sheets Range object
 * @returns {string} Text as HTML.
 * @customfunction
 */
function richTextToHtml(range) {
  const runs = range.getRichTextValue().getRuns();
  const formattedRuns = runs.map((run) => {
    const attr = {
      style: '',
    };
    const text = run.getText();
    const link = run.getLinkUrl();
    let parentTag = 'span';
    if (link) {
      parentTag = 'a';
      attr.href = link;
    }

    const style = run.getTextStyle();
    const styles = {
      'font-family': `'${style.getFontFamily()}'`,
      'font-size': `${style.getFontSize()}px`,
      color: style.getForegroundColor(),
    };
    attr.style = Object.entries(styles)
      .map(([key, val]) => `${key}: ${val}`)
      .join('; ');

    let tags = [];
    if (style.isBold()) {
      tags.push('b');
    }
    if (style.isItalic()) {
      tags.push('i');
    }
    if (style.isUnderline()) {
      tags.push('u');
    }
    if (style.isStrikethrough()) {
      tags.push('strike');
    }
    const headTags = tags.length ? `<${tags.join('><')}>` : '';
    const closeTags = tags.length ? `</${tags.join('></')}>` : '';
    const attrStr = Object.entries(attr)
      .map(([key, val]) => `${key}="${val}"`)
      .join(' ');

    const mainTag = `<${parentTag} ${attrStr}>${headTags}${text}${closeTags}</${parentTag}>`;
    const lineBreakFormattedStr = mainTag.replace(/[\r\n]/g, '<br>');
    return lineBreakFormattedStr;
  });

  return formattedRuns.join('');
}