首页 > 解决方案 > 将格式化文本添加到 Google Doc

问题描述

我有一个带有表单回复的 Google 表格。我创建了一些代码,以便每次完成表单时,结果都会填充 Google Doc。这工作正常。

但是,我也想将文本添加到我的 Google Doc 中,我使用以下方法完成:

function myFunction(e) {
  var doc = DocumentApp.create('File');
  var text = 'insert text here';
  body.appendParagraph(text);
  doc.saveAndClose();
}

但是,此文本仅作为纯文本添加,我想格式化此文本。具体来说,我想添加文本,使其在文档正文中以粗体、下划线和居中对齐

我该怎么做呢?

经过一些互联网搜索和 SO 搜索后,我尝试添加 html(例如,<b> </b>)并尝试了text.setBold(true). 这些方法都不起作用。

我承认我对 Google 脚本编辑器中的编码知之甚少,所以我完全不知道该怎么做。我很幸运,我得到了所有表单响应来填充一个命名的 Google Doc 文件!

标签: google-apps-scriptformattinggoogle-docs

解决方案


这是我最近创建的文档片段:

    var nameStyle={};
    nameStyle[DocumentApp.Attribute.FONT_SIZE]=8;
    nameStyle[DocumentApp.Attribute.BOLD]=true;
    nameStyle[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
    var valStyle={};
    valStyle[DocumentApp.Attribute.FONT_SIZE]=12;
    valStyle[DocumentApp.Attribute.BOLD]=false;
    valStyle[DocumentApp.Attribute.FOREGROUND_COLOR]='#cc0000';
    body.appendParagraph('Basic Project Data').setAttributes(hdg1Style);
    var p1=body.appendParagraph(Utilities.formatString('%s: ','PID')).setAttributes(nameStyle);
    var p2=body.appendParagraph(Utilities.formatString('%s',selObj.pid)).setAttributes(valStyle);
    p2.merge();
    for(var i=0;i<basicDataA.length;i++){
      var par1=body.appendParagraph(Utilities.formatString('%s: ',basicDataA[i][0])).setAttributes(nameStyle);
      var par2=body.appendParagraph(Utilities.formatString('%s',basicDataA[i][1])).setAttributes(valStyle);
      par2.merge();
    }

注意,appendParagraph 先是setAttributes。


推荐阅读