首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试创建一个脚本,自动填充来自谷歌工作表的屏蔽超链接的谷歌文档

尝试创建一个脚本,自动填充来自谷歌工作表的屏蔽超链接的谷歌文档
EN

Stack Overflow用户
提问于 2020-01-09 03:42:25
回答 1查看 41关注 0票数 0

例如,我有一个google表单,格式如下,第1行到第n行

文档文本超链接遮罩文本

&CAT跳跃1& https://i.imgur.com/2oTdDKF.jpg CAT跳跃1

&DOG跳跃1和https://i.imgur.com/IhpYydt.jpg?1 DOG跳跃1

我有一个谷歌文档,里面有这样的信息:

猫是很好的跳跃者,猫跳1&.狗也跳得很高,狗跳1&。

我希望结果是这样的:

猫是很好的跳跃CAT JUMPS 1。狗也会跳得很高,DOG JUMPS 1

我以前没有做过谷歌脚本。我知道如何通过脚本将文本转换为超链接,但我不知道如何让它在google工作表中查找数据,或者让它搜索文档文本并替换文本。有没有人对我应该在哪里找到如何做到这一点有一些指导?

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

发布于 2020-01-09 08:09:56

有两种方法可以做到这一点。

选项1

正如在https://www.reddit.com/r/GoogleAppsScript/comments/elx0qh/trying_to_make_a_script_that_auto_fills_a_google/中提到的,您可以:

  • 您可以使用findText通过正则表达式进行搜索。例如,对于每个找到的记录,删除前导和尾随的&
  • This将为您提供查找字符串。使用它从Google sheet
  • 中查找替换值,然后使用replaceText替换字符串

示例:

代码语言:javascript
运行
复制
// get the lookup data from the spreadsheet
var lookupData = SpreadsheetApp.openById("...").getSheetByName("...").getDataRange().getDisplayValues();

// first row is header row
var lookupDataHeaderRow = lookupData.shift();

// get document body from the doc
var documentBody = DocumentApp.openById("...").getBody();

// we will continously search the document until there are no more found results
var searchResult = null;
while(searchResult = documentBody.findText("&.*?&", searchResult))
{
  // get the found element
  var foundElement = searchResult.getElement();

  // make sure it is a text type
  if(foundElement.getType() !== DocumentApp.ElementType.TEXT) continue;

  // get the text object of the found element
  var foundText = foundElement.asText();

  // extract the search string
  var documentText = foundText.getText().match("&(.*?)&")[1];

  // look for the documentText in the lookup data
  var foundLookupRows = lookupData.filter(function(row){
    return row[lookupDataHeaderRow.indexOf("DOCUMENT TEXT")] == documentText;
  });

  // make sure we found it in the lookup data
  if(foundLookupRows.length == 0) continue;

  // first replace the found text with the masking text of the first found row
  foundText.setText(foundLookupRows[0][lookupDataHeaderRow.indexOf("MASKING TEXT")]);

  // make it a hyperlink
  foundText.setLink(foundLookupRows[0][lookupDataHeaderRow.indexOf("HYPERLINK")]);
}

选项2

与上面类似,但是:

浏览Google工作表中的每一行-在文档中查找文档文本的那一行,并生成适当的replacements

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59652797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档