【问题标题】:Replacing a text placeholder with a chart from a sheet用工作表中的图表替换文本占位符
【发布时间】:2017-10-12 04:15:47
【问题描述】:

我有一个脚本,它应该使用 Google 表格中的各种值填充 Google 文档正文中的一系列占位符。我希望合并到模板中的对象之一是 EmbeddedChartBuilder 对象:

var chart = sheet.newChart()
                 .addRange(range)
                 .setChartType(Charts.ChartType.BAR)
                 .setPosition(i, 6, 0, 0)
                 .setOption('legend.position', 'none')
                 .setOption('height', 50)
                 .setOption('width', 700)
                 .setOption('colors', ['black', 'white'])
                 .setOption('hAxis.minValue', 0)
                 .setOption('hAxis.maxValue', 10)
                 .setOption('backgroundColor.fill', 'white')
                 .setOption('hAxis.gridlines.color', 'white')
                 .setOption('hAxis.gridlines.count', 0);
sheet.insertChart(chart.build());

合并代码如下:

body.replaceText('{name}', company.name);
body.replaceText('{score}', company.score);
body.replaceText('{applyTime}', company.applyTime);
body.replaceText('{confEmail}', company.confEmail);
body.replaceText('{mobiFriendly}', company.mobiFriendly);
body.replaceText('{chart}', chart);

最后一行 body.replaceText('{chart}', chart); 当然只是简单地将 Doc 中的占位符替换为“EmbeddedChartBuilder”。

有没有办法将图表作为图像或其他东西插入占位符?如果有,怎么做?

【问题讨论】:

    标签: javascript google-apps-script google-sheets google-docs


    【解决方案1】:

    首先,将.build() 放在定义chart 变量的链末尾更符合逻辑。毕竟,您要插入图表,而不是图表构建器。

    当然,尝试使用 replaceText 函数插入图表会强制将其转换为“EmbeddedChart”字符串。相反,在适当的元素上使用appendInlineImageinsertInlineImage。我将使用前者,因为它更简单:它只是将图像附加到应用它的元素的末尾。

    var chart = sheet.newChart()........build();
    var found = body.findText('{chart}');
    if (found) {
      found.getElement().getParent().appendInlineImage(chart);
      body.replaceText('{chart}', '');
    }
    

    这里,findText 检索指向 {chart} 的 RangeElement;然后我们得到包含该字符串的元素(文本),然后是它的父级(可能是一个段落,但也可能是一个 ListItem 等)。图像被附加到父级,最后字符串 {chart} 用replaceText 删除。

    这假定字符串 {chart} 位于其元素的末尾(很可能,它位于自己的段落中)。

    【讨论】:

    • 谢谢。问完这个问题,就在我正要回答这个问题的时候,我意识到了很多这样的事情,但是你的措辞可能比我想象的要好!
    猜你喜欢
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 2010-09-29
    • 2012-12-07
    • 1970-01-01
    相关资源
    最近更新 更多