如何使用 Google Script 在 Google Docs 中添加超链接 [英] How to add a hyperlink in a Google Docs using a Google Script
问题描述
我一直使用 insertText() 函数,但现在我想在我的 google 文档中写一个链接.理想的情况是能够用 HTML 编写,但我不知道如何...使用 insertText() 函数似乎不可能.
I have always used the insertText() function, but now I want to write a link in my google docs. The ideal would be to be able to write in HTML, but I don't know how.. it seems that it is not possible with the insertText() function.
我该怎么做?
推荐答案
你应该能够像这样使用 setFormula 和 Hyperlink 公式:
You should be able to use setFormula and the Hyperlink formula like so:
var value = '=HYPERLINK("www.google.com", "Google")';
SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName("Sheet1")
.getRange("A1")
.setFormula(value);
看起来我误读了这个问题.试试这个:
Looks like I misread the question. Try this instead:
DocumentApp.getActiveDocument()
.getBody()
.editAsText()
.insertText(0, "link text")
.setLinkUrl("www.google.com");
编辑 2: 看起来 .setLinkUrl()
正在影响整个正文,而不是插入的文本.如果将链接文本放入一个变量中,并使用变量的长度来标记链接区域,它应该可以工作.试试这个:
Edit 2: Looks like .setLinkUrl()
is effecting the whole body, not the text inserted. If you put the link text into a variable and use the length of the variable to mark the link area, it should work. Try this instead:
function insertLink() {
var text = "link text
";
var url = "www.google.com";
DocumentApp.getActiveDocument()
.getBody()
.editAsText()
.insertText(0, text)
.setLinkUrl(0, text.length, url);
}
这篇关于如何使用 Google Script 在 Google Docs 中添加超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!