![](/img/trans.png)
[英]How to read contents of a Google Doc from the script of a Google Sheet?
[英]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
findText
使用正則表達式進行搜索。 例如, body.findText("&.*&")
。&
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
與上面類似,但:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.