How to add a hyperlink in a Google Docs using a Go

2019-02-09 06:32发布

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.

How can I do that ?

2条回答
Rolldiameter
2楼-- · 2019-02-09 07:21

I am using this script, this is working Calomun 1 Row > 2.

    function InsertLink(e)
    {
      var actSht = e.source.getActiveSheet();
      if (actSht.getName() == ['SheetName']){

      var activeCell = actSht.getActiveCell(); //Detec the ActiveCell

      //var activeCell = event.range;
      var activeCellValue = e.value;

      var column = activeCell.getColumn();
      var colNums  = [1]; //Columns, whose edit is considered
      if(colNums.indexOf(column) == -1) return; //If column other than considered then return

      var row = activeCell.getRow();
      if(row < 2)   return; //If header row then return

      var length = String(activeCellValue).length;

      if (!e.value)
      {
        activeCell.setValue()
      }
      else if(length > 4)
      {
        activeCell.setValue('=HYPERLINK' + '("http://otrs/otrs/index.pl?Action=AgentTicketZoom;TicketNumber='+activeCellValue+'";"'+activeCellValue+'")'        );
      }
    }
    }
查看更多
看我几分像从前
3楼-- · 2019-02-09 07:26

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);

Edit: Looks like I misread the question. Try this instead:

DocumentApp.getActiveDocument().getBody().editAsText().insertText(0, "link text").setLinkUrl("www.google.com");

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\n";
  var url = "www.google.com";
  DocumentApp.getActiveDocument().getBody().editAsText().insertText(0, text).setLinkUrl(0, text.length, url);
}
查看更多
登录 后发表回答