簡體   English   中英

試圖制作一個腳本,用谷歌工作表中的屏蔽超鏈接自動填充谷歌文檔

[英]Trying to make a script that auto fills a google doc with masked hyperlinks from a google sheet

例如,我有一個格式如下的谷歌工作表,第 1 行到第 n 行

文檔文本超鏈接屏蔽文本

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

&狗跳1& https://i.imgur.com/IhpYydt.jpg?1狗跳1

我有一個谷歌文檔,其中包含如下信息:

貓是很好的跳投手&CAT JUMPS 1&。 狗也跳得很高&DOG JUMPS 1&。

我希望結果是這樣的:

貓是好跳投CAT JUMPS 1 狗也跳得很高DOG JUMPS 1 .

我以前沒有做過谷歌腳本。 我知道如何通過腳本將文本變成超鏈接,但我不知道如何讓它查看谷歌表中的數據或讓它搜索文檔文本並替換文本。 有沒有人對我應該在哪里尋找如何做到這一點有一些指導?

謝謝您的幫助。

有兩種方法可以做到這一點。

選項1

https://www.reddit.com/r/GoogleAppsScript/comments/elx0qh/trying_to_make_a_script_that_auto_fills_a_google/ 中所述,您可以:

  • 您可以使用findText使用正則表達式進行搜索。 例如, body.findText("&.*&")
  • 然后對於每個找到的記錄,刪除前導和尾隨&
  • 這將為您提供查找字符串。 使用它從 Google 表格中查找替換值
  • 然后使用replaceText來替換字符串

例子:

// 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 表格中的每一行 - 具有查找值的那一行
  • 在文檔中搜索 DOCUMENT TEXT 並進行適當的替換

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM